我想在客户订单创建触发器数据库,在那里每个客户都有几个数量级和每个订单都有几个项目。INSERT触发器:问题与constarint
我打算创建一个触发器,以确保
所有订单的地方通过同一客户的总数不能 超过10000
如何上面创建INSERT触发器约束。
这是我提供的示例数据的SQL文件。
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;
CREATE TABLE customers
(`id` int not null auto_increment primary key, `first_name` varchar(64), `last_name`varchar(64));
INSERT INTO customers(`first_name`, `last_name`)VALUES('Jhon', 'Doe');
CREATE TABLE items
(`id` int not null auto_increment primary key,`item` varchar(64),`price` decimal(19,2));
INSERT INTO items(`item`, `price`)VALUES('Item1', 10.5),('Item2', 25);
CREATE TABLE orders
(`id` int not null auto_increment primary key, `date` date, `customer_id` int,`status` int not null default 1, -- 1 new constraint fk_customer_id foreign key (customer_id) references customers (id));
INSERT INTO orders(`date`, `customer_id`, `status`)VALUES(CURDATE(), 1, 1);
CREATE TABLE order_items(`id` int not null auto_increment primary key,
`order_id` int not null, `item_id` int not null, `quantity` decimal(19,3) not null, `price` decimal(19,3) not null,
constraint fk_order_id foreign key (order_id) references orders (id),
constraint fk_item_id foreign key (item_id) references items (id));
INSERT INTO order_items(`order_id`, `item_id`, `quantity`, `price`)VALUES
(1, 1, 2, 10.5),(1, 2, 4, 25);
;
任何帮助,非常感谢。
我正在使用MySQL数据库 – webtale
您可以使用检查约束,而不是触发器 –
为什么在触发器中。考虑不允许插入呼叫。更好的是,当他们点击下订单时,发出通知“你不能下订单,你已经从我们这里买了太多” – Drew