我正在进行查询,其中我有三个表要加入,但第三个表可能有也可能没有相关记录。
我目前有:
SELECT table1.val, table2.val, table.3.val
FROM
table1
LEFT JOIN table2
ON table1.val = table2.val
LEFT JOIN table3
ON table.3.val = table2.val
WHERE
table1.name = "name"
AND table3.name = 'certain name'
ORDER BY table1.val ASC
如何编写此代码,以便'certain name'
中table3
中不存在WHERE
,SELECT
和{{1}}条款中省略了该部分?我实际上选择了几个字段,但这应该充分证明了这个问题。
答案 0 :(得分:1)
如果您的意思是结果表单table3
应该只显示,table3.val
等于table2.val
并且table3.name
应该等于'certain name'
那么这适合你:
SELECT table1.val, table2.val, table.3.val
FROM table1
LEFT JOIN table2
ON table1.val = table2.val
LEFT JOIN table3
ON table.3.val = table2.val AND table3.name = 'certain name'
WHERE table1.name = "name"
ORDER BY table1.val ASC
毕竟,这是LEFT JOIN
的目的......