我正在使用mysql数据库,如果产品代码已经存在于tableA中,我正试图将记录插入tableB。
我认为CASE语句会工作,但我在网上找不到任何进一步的帮助。以下是目前为止的内容:
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
非常感谢任何帮助。欢呼声
您只需要编写一个常规的旧插入语句:
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'
此处:
INSERT INTO tableB
(productcode)
SELECT productcode
FROM tableC c
WHERE EXISTS (SELECT productcode
FROM tableA a
WHERE a.productcode = c.productcode)
或者如果你在item_codes上放了一个外键,你可以用通常的方式插入记录
INSERT INTO tableB(item_id, serial_number, used) VALUES ('$iid','$sns','$used')
并在发生时捕获异常…
参见:处理PHP外键异常