tags:

views:

42

answers:

2

Can someone please help me with how I can add several different queries to one query with OR?

I have posts that I only want to show to user that are allowed to see it OR groups that are allowed to see it OR every on.

SELECT p.*, c.name, cb.categoryId FROM Posts AS p
LEFT JOIN CategoryBindings AS cb ON cb.postId = p.id
LEFT JOIN Categories AS c ON c.id = cb.categoryId
LEFT JOIN UserBindings AS ub ON ub.postId = p.id
WHERE ub.userId = 1

SELECT p.*, c.name, cb.categoryId FROM Posts AS p
LEFT JOIN CategoryBindings AS cb ON cb.postId = p.id
LEFT JOIN Categories AS c ON c.id = cb.categoryId
LEFT JOIN GroupPostBindings AS gpb ON gpb.postId = p.id
LEFT JOIN GroupBindings AS gp ON gp.groupId = gpb.groupId
WHERE gp.userId = 1

SELECT p.*, c.name, cb.categoryId FROM Posts AS p
LEFT JOIN CategoryBindings AS cb ON cb.postId = p.id
LEFT JOIN Categories AS c ON c.id = cb.categoryId
WHERE p.public = 1

How can I add these three queries to one query?

+1  A: 

Have you looked into using UNION? There may be a more efficient way of doing it, admittedly - that was just the first thing that came to mind.

Jon Skeet
+3  A: 
SELECT p.*, c.name, cb.categoryId FROM Posts AS p
LEFT JOIN CategoryBindings AS cb ON cb.postId = p.id
LEFT JOIN Categories AS c ON c.id = cb.categoryId
LEFT JOIN UserBindings AS ub ON ub.postId = p.id
LEFT JOIN GroupPostBindings AS gpb ON gpb.postId = p.id
LEFT JOIN GroupBindings AS gp ON gp.groupId = gpb.groupId
where p.public = 1 or ub.userId = 1 or gp.userId = 1

should work, assuming your joins will always return a value (either 0 or 1 it would seem), and not exclude rows

Lazy Bob
It worked like a charm. I believe that all the joins made me think that it would be much harder than it really is and then it was so easy and I feel stupid for even asking the question. Thank you.
unkown