sql—如何基于其他表中的数据在表上创建sqlite触发器?

2q5ifsrm  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(251)

我有两张table-

part(partID, brand, price, size)
consists_of(customerID, partID, quantity, price, shipdate)
                        |
                        FK part.ID from part

part 永远不会被改变/更新,但是 consists_of 将。
如何在上添加[插入前?]触发器 consists_of 检查是否 consists_of.price 对于每个条目小于或等于 consists_of.quantity * part.price 对于那个特殊的 consists_of.partID 如果不是这样的话会引起流产吗?
或者,
如何添加[插入后?]触发器 consists_of 是的 INSERT INTO consists_of(price) VALUES (...) 其中 consists_of.price 等于 consists_of.quantity * part.price 为了这个 consists_of.partID ?

tjjdgumg

tjjdgumg1#

如果我理解正确,你可以选择 part.price 在子查询和计算中 part.price * consists_of.quantitiy .
插入前

CREATE TABLE part(part_id INTEGER, price INTEGER);
CREATE TABLE consists_of(customer_id INTEGER, part_id INTEGER, quantity INTEGER, price INTEGER);

INSERT INTO part VALUES(10, 50);
INSERT INTO part VALUES (20, 1000);

CREATE TRIGGER IF NOT EXISTS raise_if_consists_of_price_too_expensive
AFTER INSERT ON consists_of
WHEN new.price > (SELECT part.price * new.quantity FROM part WHERE part.part_id = new.part_id)
BEGIN
  SELECT RAISE (ABORT, 'too expensive.');
END;

 -- OK
INSERT INTO consists_of(customer_id, part_id, quantity, price)
VALUES(10050, 20, 31, 100);
 -- OK
INSERT INTO consists_of(customer_id, part_id, quantity, price)
VALUES(80030, 10, 9, 50 * 9);
 -- Raise abort
INSERT INTO consists_of(customer_id, part_id, quantity, price)
VALUES(80099, 10, 9, 50 * 9 + 1);

插入后

CREATE TABLE part(part_id INTEGER, price INTEGER);
CREATE TABLE consists_of(customer_id INTEGER, part_id INTEGER, quantity INTEGER, price INTEGER);

INSERT INTO part VALUES(10, 50);
INSERT INTO part VALUES (20, 1000);

CREATE TRIGGER IF NOT EXISTS fill_consists_of_price
AFTER INSERT ON consists_of
BEGIN
  UPDATE consists_of
  SET
  price = (
    SELECT consists_of.quantity * part.price
    FROM part
    WHERE part.part_id = consists_of.part_id
  )
  WHERE customer_id = new.customer_id AND part_id = new.part_id
  ;
END;

INSERT INTO consists_of(customer_id, part_id ,quantity)
VALUES(10050, 20, 31);

INSERT INTO consists_of(customer_id, part_id ,quantity)
VALUES(80033, 10, 9);

相关问题