我对SQL比较陌生,并且有以下问题。我有以下代码:
Select * from table1
LEFT JOIN table2 ON table1.name = table2.name and table1.id = table2.id
LEFT JOIN (SELECT id FROM table2 GROUP BY id) newtable ON table1.id = newtable.id
由于两个左联接都使用同一表中的数据,是否可以将两个联接合并为一个?在这种情况下,过滤器将如何工作?
答案 0 :(得分:0)
如果您的目标只是基于不同的值加入table2
,则可以使用WHERE
和GROUP BY
:
Select
*
from table1 t1
LEFT JOIN table2 t2
ON t1.name = t2.name and t1.id = t2.id
WHERE t1 id in (SELECT s2.id FROM table2 s2 GROUP BY s2.id)