SQL - 如果记录存在于tableA中,则插入到tableB中

Chr*_*ris 1 php mysql sql

我正在使用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
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢.干杯

Der*_*omm 6

您只需要编写一个常规的旧插入语句:

insert into tableB(item_id, serial_number, used)
select '$iid', '$sns', '$used'
where exists (select 1 from tableA where item_code = '$pcode')
Run Code Online (Sandbox Code Playgroud)