如果 idTable2 存在,如何在 table3 (idTable1, idTable2) 中插入一行

问题描述 投票:0回答:1

我在 SQL 方面遇到问题。 我有3张桌子

  • 表1(id,....,name='name1')
  • Table2(id,....,guid='guidTable2')
  • 表3(idTable1,idTable2)

我需要一个sql脚本向包含table1id和table2id的table3添加一行,为了检索auto_increment id,我有table1的名称数据(始终唯一)和表2的guid数据(也始终唯一)。

我想到了这样的事情:

INSERT INTO table3 ( table1id, table2id ) 
VALUES((SELECT id FROM table1 WHERE name = 'name1'), (SELECT id FROM table2 WHERE guid='guidTable2'))

但是,在这段代码中我无法测试 :

返回的行是否
SELECT id FROM table2 WHERE guid='guidTable2'

为空。

如果 idTable2 为空,我只想跳过插入。

我有很多插入要在同一个脚本中运行,我不希望出现任何错误。如果可能的话,使用日志来找出表 2 中哪些行不存在,但这是一个改进。

有什么想法吗? 谢谢

如果id为空,如何跳过插入

sql sql-server insert
1个回答
0
投票

在插入之前,您可以使用 LEFT JOIN 检查该行是否存在于 table2 中:

INSERT INTO table3 (table1id, table2id)  
SELECT t1.id, t2.id
FROM table1 t1
LEFT JOIN table2 t2 ON t2.guid = 'guidTable2'
WHERE t1.name = 'name1'
  AND t2.id IS NOT NULL

仅当 table2 中有匹配行时才会插入。要获取不匹配的行,您可以选择 t2.id IS NULL 的行:

SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.guid = 'guidTable2'
WHERE t1.name = 'name1'
  AND t2.id IS NULL

因此,通过在插入之前执行 LEFT JOIN 并检查 NULL,您可以跳过在 table2 行不存在的地方插入行。然后通过检查 IS NULL,您可以看到哪些没有匹配项可以在需要时记录。

© www.soinside.com 2019 - 2024. All rights reserved.