SQL - 如果表中存在记录,则插入表中

时间:2011-07-27 13:09:50

标签: 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

任何帮助非常感谢。 干杯

4 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:1)

insert into tableB(item_id, serial_number, used)
select item_id, '$sns', 1
from tableA where item_code = '$pcode'

答案 2 :(得分:1)

下面:

INSERT INTO tableB
            (productcode)
SELECT productcode
FROM   tableC c
WHERE  EXISTS (SELECT productcode
               FROM   tableA a
               WHERE  a.productcode = c.productcode) 

答案 3 :(得分:0)

或者如果你在item_codes上放了一个外键,你可以用通常的方式插入记录

INSERT INTO tableB(item_id, serial_number, used)  VALUES ('$iid','$sns','$used')

并在发生异常时捕获异常......

请参阅:Handling foreign key exceptions in PHP

这种方法的好处是数据库会自动为您执行规则。

相关问题