如何将where子句添加到右外连接并且左外连接?

时间:2013-09-01 19:59:44

标签: sql mysqli left-join right-join

我正在使用以下sql(对于mysqli)并且想知道我如何以及在哪里放置where子句。所以我可以举例说明id = 2的所有结果?

SELECT * 
FROM public_tips 
LEFT OUTER JOIN likes
USING (id) 
UNION 
SELECT * 
FROM likes 
RIGHT OUTER JOIN public_tips
USING (id)

我试过了

SELECT * 
FROM public_tips WHERE id=2
LEFT OUTER JOIN likes
USING (id) 
UNION 
SELECT * 
FROM likes WHERE id=2
RIGHT OUTER JOIN public_tips
USING (id)

但我收到语法错误!

1 个答案:

答案 0 :(得分:0)

where子句位于from子句之后,join子句是from子句的一部分:

SELECT * 
FROM public_tips
LEFT OUTER JOIN likes
USING (id) 
WHERE public_tips.id=2
UNION 
SELECT * 
FROM likes 
RIGHT OUTER JOIN public_tips
USING (id)
WHERE public_tips.id=2