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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.