如何在INSERT之前检查mysql中的值

时间:2011-09-05 11:29:02

标签: mysql

Hio Guys,我有以下SQL查询;

INSERT INTO ps_ext_mod (id_order,product_reference,id_customer,email)
SELECT d.id_order, d.product_reference, o.id_customer, c.email
FROM ps_orders o
INNER JOIN ps_order_detail d ON d.id_order = o.id_order
INNER JOIN ps_customer c ON c.id_customer = o.id_customer

如果id_order已经存在且要插入的值,我需要检查表ps_ext_mod。如果是的话,那就不要插入它。

3 个答案:

答案 0 :(得分:3)

您可以加入表格并查找连接失败的位置,即:

INSERT INTO ps_ext_mod (id_order,product_reference,id_customer,email)
SELECT d.id_order, d.product_reference, o.id_customer, c.email
FROM ps_orders o
INNER JOIN ps_order_detail d ON d.id_order = o.id_order
INNER JOIN ps_customer c ON c.id_customer = o.id_customer
LEFT JOIN ps_ext_mod em ON em.id_order = d.id_order
WHERE em.id_order IS NULL

答案 1 :(得分:2)

如果你想在纯SQL中这样做,那么有:

If (SELECT count(*) FROM ps_ext_mod WHERE id_order = ?) == 0) THEN (Other SQL)

http://dev.mysql.com/doc/refman/5.0/en/if-statement.html

答案 2 :(得分:0)

INSERT INTO ps_ext_mod (id_order,product_reference,id_customer,email)
SELECT d.id_order, d.product_reference, o.id_customer, c.email
FROM ps_orders o
INNER JOIN ps_order_detail d ON d.id_order = o.id_order
INNER JOIN ps_customer c ON c.id_customer = o.id_customer
LEFT JOIN ps_ext_mod m on m.id_order = d.id_order 
where m.id_order is null;