我想在客戶訂單創建觸發器數據庫,在那裏每個客戶都有幾個數量級和每個訂單都有幾個項目。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