[英]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. 我正在使用mysql数据库,并且如果产品代码已存在于tableA中,则尝试将记录插入到tableB中。
I think a CASE statement would work, but I can't find any further help on the web. 我认为可以使用CASE语句,但在网上找不到更多帮助。 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 或者,如果您将外键放在item_codes上,则可以按照通常的方式插入记录
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 请参见: 在PHP中处理外键异常
the benifit of this approach is that the database is automatically enforcing the rule for you. 这种方法的好处是数据库会自动为您执行该规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.