我是MySQL新手。如果表2中不存在记录,则在将其插入表1时出现问题。表1和表2的格式为:

table1

dep_id  start     stop     modified deleted
1       23456789  167921525   Yes      No
2       34567812  345678145   Yes      No
3       32789054  327890546   No       No


table2

start     stop     modified deleted
23456789  167921525  No       No
34567823  345678145  No       No
32789053  727890546  No       No

我试图将值插入到表1的“开始”和“停止”字段值中,前提是该字段值不存在于表2的“开始”和“停止”列中。如果它存在,我需要抛出一个错误。
这些表没有主键外键关系。
很抱歉,我不知道正确的语法,但我必须在mysql和php中这样做。
Replace Into into table1 set 'start'=> $start,'stop' => $stop
(select 'start','stop' from table2 where table1.start and table1.stop not in table2.start and table2.stop);

在插入到表1之前,如何查询这两个表以检查表1.start和表1.stop字段是否与表2.start和表2.stop不匹配?

最佳答案

你可以:

INSERT INTO table1 (start, stop)
SELECT    a.*
FROM      (SELECT 123456789 start, 234567890 stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE     b.start IS NULL

其中123456789234567890分别是startstop的输入值。
然后,您可以根据正在使用的db接口(pdo、mysqli等)检查受影响的行数或行数。如果是0,则未插入任何记录,否则,将发生插入。
SQLFiddle Demo

关于mysql - 如果表2中不存在,如何插入表1?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11998585/

10-10 09:44