我有两张桌子:
表1
id code
1 a
2 b
3
表2
id code
4 a
5 b
6
表3
id id1
1 4
2 5
我基本上想要根据table1.name = table2.name
插入表3,其中包含表1和表2的ID。
INSERT INTO table3(id,id1)
SELECT t1.id,t2.id FROM table1 t1, table2 t2 where t1.name=t2.name;
然而,表1和表2的第3行都有空代码,我将如何比较null = null
无效。
帮助表示赞赏..
答案 0 :(得分:1)
只需添加(t1.name IS NULL AND t2.name IS NULL)
测试:
INSERT INTO table3 (id, id1)
SELECT t1.id, t2.id
FROM table1 t1
INNER JOIN table2 t2 ON t1.name = t2.name OR (t1.name IS NULL AND t2.name IS NULL);
答案 1 :(得分:1)
正如我几天前所了解的那样,MySQL支持语法增强<=>
来将NULL比较为相等:
INSERT INTO table3(id,id1)
SELECT t1.id,t2.id
FROM table1 t1 JOIN table2 t2
ON t1.name <=> t2.name;
编辑:
答案 2 :(得分:0)
使用内部联接
INSERT INTO table3(id,id1) SELECT t1.id, t2.id
FROM table1 t1
INNER JOIN table2 t2 ON t1.name = t2.name OR (t1.name IS NULL AND t2.name IS NULL);
答案 3 :(得分:0)
在oracle中,使用nvl()将null值转换为较少使用的字符。
INSERT INTO table3(id,id1)
SELECT t1.id,t2.id
FROM table1 t1, table2 t2
WHERE nvl(t1.code,'$$')=nvl(t2.code,'$$');