开发者

How to check against a value in mysql before INSERT

Hio Guys, I have the following SQL query;

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

What I need to happen is to check the table ps_ext_mod if id_order already exists with the value to be inserted. If it does, then dont insert it.


You can just join back to the table and look for where the join fails, i.e.:

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


If you want to do it in pure SQL then there is :

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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜