我在连接2个具有不同行数的表时遇到问题。我尝试了LEFT JOIN
,但它不起作用,我认为这是因为ID_advertentie
。
查询:
SELECT * FROM table1
LEFT JOIN table2 ON table1.ID_kenmerk = table2.ID_kenmerk
WHERE table1.categorie = 1 AND table2.ID_advertentie = 17
如何使用表格示例下面提到的结果编写一个查询?
Table 1
ID_kenmerk Categorie Naam_kenmerk Plaatje_kenmerk Data_type
1 - 1 - Kenmerk a - plaatje1.gif - INT
2 - 1 - Kenmerk b - plaatje2.gif - BOOL
3 - 1 - Kenmerk c - Plaatje3.jpg - INT
4 - 1 - Kenmerk d - plaatje4.jpg - VARCHAR
5 - 2 - Kenmerk F - plaatje1.gif - INT
6 - 2 - Kenmerk G - plaartje2.gif - VARCHAR
Table 2
ID_kenmerk_data ID_kenmerk ID_advertentie value
1 - 1 - 17 - Test1
2 - 2 - 17 - Test2
3 - 3 - 17 - Test3
4 - 1 - 23 - lala1
5 - 2 - 23 - lala2
6 - 3 - 23 - ajdk2
结果查询(WHERE ID_advertentie = 17
!)
ID_kenmerk Naam_kenmerk value
1 - Kenmerk a - Test1
2 - Kenmerk b - Test2
3 - Kenmerk c - Test3
4 - Kenmerk d - NULL
答案 0 :(得分:3)
SELECT *
FROM table1
LEFT JOIN table2 ON table1.ID_kenmerk = table2.ID_kenmerk AND table2.ID_advertentie = 17
WHERE table1.categorie = 1
您在WHERE
子句中使用的任何内容也可以在ON
子句中使用。但是,将table2.ID_advertentie = 17
从WHERE
移动到ON
子句会在右侧添加一个NULLed行,如果没有匹配而不是消除它。
(编辑)替代方法:
SELECT *
FROM table1
LEFT JOIN table2 ON table1.ID_kenmerk = table2.ID_kenmerk
WHERE table1.categorie = 1 AND (table2.ID_kenmerk_data IS NULL OR table2.ID_advertentie = 17)
答案 1 :(得分:2)
你是对的,你需要一个LEFT JOIN
。但是当您执行(LEFT
)OUTER JOIN
时,右表中的任何WHERE
条件都会取消外连接。
解决方案是将有关(右侧)table2
(table2.ID_advertentie = 17
一个)的条件从WHERE
移至ON
子句:
SELECT *
FROM table1
LEFT JOIN table2
ON table1.ID_kenmerk = table2.ID_kenmerk
AND table2.ID_advertentie = 17 --- this condition moved
WHERE table1.categorie = 1