简体   繁体   English

SQL触发器检查行是否已经存在

[英]SQL trigger to check if row already exists

So I have two tables(orders and fabric_order). 所以我有两个表(orders和fabric_order)。 This sql is triggered after an insert is done on another table. 在另一个表上完成插入后,将触发此sql。 I don't want duplicate rows, so I wanna check the table (fabric_orders) if already has a row with a code equal to the code from the other table (orders) and insert into table (fabric_order) only if doesn't exist the same code 我不希望重复的行,所以我想检查表(fabric_orders)是否已包含一行代码,该行的代码等于其他表(订单)中的代码,并且仅当不存在该行时才插入表(fabric_order)中。相同的代码

IF NOT EXISTS
(
    select code 
    from orders
    WHERE code=fabric_order.code
)
INSERT INTO fabric_order (order_id, code, start_date)
SELECT(id, code, deliver_date)
FROM orders

桌子

You don't need to have a trigger for it a INSERT ... SELECT ... LEFT JOIN .. should also have the same results. 您不必为此触发INSERT ... SELECT ... LEFT JOIN ..也应具有相同的结果。

INSERT INTO fabric_order AS fabric_order_outer (
     fabric_order_outer.order_id
   , fabric_order_outer.code
   , fabric_order_outer.start_date
)
SELECT(
     orders.id
   , orders.code
   , orders.deliver_date
)
FROM orders
LEFT JOIN 
  fabric_order AS fabric_order_inner
ON
 orders.code = fabric_order_inner.code
WHERE
 fabric_order_inner.order_id IS NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM