简体   繁体   English

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

[英]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.

相关问题 如何在插入tableB之前检查tableA中是否存在值? - How to check if a value exists in tableA before inserting in tableB? 如何将Mysql一次一次插入到2个表中,其中tableA具有唯一的userID和tableB重复的userID - How to Mysql INSERT into 2 tables at once where tableA has unique userID and tableB recurring userID 从tableA和tableB选择记录,其中tableA.id = tableB.id,一次从tableA记录 - select records form tableA and tableB where tableA.id = tableB.id, records from tableA once 插入SQL表或更新记录(如果存在) - Insert into SQL table or update record if exists PHP / SQL如果在数据库的该行中不存在该记录,则插入一条记录,形成一个scandir数组 - PHP/SQL insert a record if it not exists in that row on the db, form an scandir array 来自TableA的MySQLi SELECT行,其中TableB中有0行 - MySQLi SELECT rows from TableA where 0 rows in TableB 如何计算来自tableB的列,其中tableA.y = TableB.y laravel - How count a column from a tableB where tableA.y = TableB.y laravel 不存在的SQL插入 - SQL Where NOT Exists Insert 来自3个表的JOIN行WHERE tableA.column1 = tableB.column1 = tableC.column1 - JOIN rows from 3 tables WHERE tableA.column1 = tableB.column1 = tableC.column1 活动记录在值存在时省略插入 - active record omit insert when value exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM