How can I add a where clause to a right outer join union left outer join?

127 Views Asked by At

I'm using the following SQL and was wondering how and where I can put a where clause. So that I can for example bring all the results where id=2?

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

I have tried

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)

but I get a syntax error!

1

There are 1 best solutions below

1
On

The where clause goes after the from clause, and the join clauses are part of the from clause:

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