有人可以帮我解决如何使用OR向一个查询添加几个不同的查询吗?
我有一些帖子,我只想向用户显示允许查看的帖子或允许查看的帖子或每个帖子。
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
如何将这三个查询添加到一个查询中?
答案 0 :(得分:3)
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
应该有效,假设您的连接将始终返回一个值(看起来为0或1),而不是排除行
答案 1 :(得分:1)
您是否考虑过使用UNION?无可否认,这可能是一种更有效的方式 - 这只是我想到的第一件事。