SQL - if record exists in tableA, then insert into tableB
I'm using a mysql database, and I'm trying to insert a record into tableB if the product code already开发者_开发知识库 exists in tableA.
I think a CASE statement would work, but I can't find any further help on the web. Here is what I have so far:
CASE (SELECT COUNT(*) FROM tableA WHERE tableA.item_code = '$pcode') > 1
THEN INSERT INTO tableB(item_id, serial_number, used)
VALUES ('$iid','$sns','$used') END
Any help greatly appreciated. Cheers
You just need to write a regular old insert statement:
insert into tableB(item_id, serial_number, used)
select '$iid', '$sns', '$used'
where exists (select 1 from tableA where item_code = '$pcode')
insert into tableB(item_id, serial_number, used)
select item_id, '$sns', 1
from tableA where item_code = '$pcode'
Here:
INSERT INTO tableB
(productcode)
SELECT productcode
FROM tableC c
WHERE EXISTS (SELECT productcode
FROM tableA a
WHERE a.productcode = c.productcode)
or if you put a foreign key on the item_codes you could just insert the record in the usual way
INSERT INTO tableB(item_id, serial_number, used) VALUES ('$iid','$sns','$used')
and catch the exception if it happens...
see: Handling foreign key exceptions in PHP
the benifit of this approach is that the database is automatically enforcing the rule for you.
精彩评论