如何将这两个复杂的查询合并为一个没有联合的查询?
(SELECT posts.id FROM posts
INNER JOIN discussions ON discussions.post_id = posts.id
INNER JOIN companies ON discussions.company_id = companies.id
INNER JOIN subscriptions ON subscriptions.subscribable_id = companies.id AND subscriptions.subscribable_type = 'Company'
INNER JOIN users ON subscriptions.user_id = users.id WHERE users.id = 6)
UNION
(SELECT posts.id FROM posts
INNER JOIN users users_2 ON posts.analyst_id = users_2.id
INNER JOIN subscriptions ON subscriptions.subscribable_id = users_2.id AND subscriptions.subscribable_type = 'User'
INNER JOIN users ON subscriptions.user_id = users.id WHERE users.id = 6)
很明显,两个查询中的最后一个连接是相同的。只是不确定如何“或”在一起连接。
(SELECT posts.id FROM posts
INNER JOIN discussions ON discussions.post_id = posts.id
INNER JOIN companies ON discussions.company_id = companies.id
INNER JOIN subscriptions ON subscriptions.subscribable_id = companies.id AND subscriptions.subscribable_type = 'Company'
INNER JOIN users ON subscriptions.user_id = users.id WHERE users.id = 6)
UNION
(SELECT posts.id FROM posts
INNER JOIN users users_2 ON posts.analyst_id = users_2.id
INNER JOIN subscriptions ON subscriptions.subscribable_id = users_2.id AND subscriptions.subscribable_type = 'User'
INNER JOIN users ON subscriptions.user_id = users.id WHERE users.id = 6)
It should be obvious that the last join is the same in both queries.. Just not sure how to "or" together joins.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有些连接似乎是多余的:
discussions
可以直接在company_id
列上连接到subscriptions
;posts
可以直接在analyst_id
列上加入subscriptions
;在任一 SELECT 中最后一次加入
users
是不必要的,因为没有从该表中检索到任何数据,并且可以重新应用过滤器 (users.id = 6
)到subscriptions.user_id
。所以,我可能会像这样重写查询:
Some joins seem redundant:
discussions
could be joined tosubscriptions
directly on thecompany_id
column;posts
could be joined tosubscriptions
directly on theanalyst_id
column;the last join to
users
in either SELECT is unnecessary as no data is retrieved from that table and the filter (users.id = 6
) could be re-applied tosubscriptions.user_id
.So, I would probably rewrite the query like this:
这是未经测试的,但请尝试一下。让我知道它是否有效。
This is untested, but give this a try. Let me know if it works.
我认为我忽略了一些差异,但如果您只想将帖子放在第一个或第二个而不使用 UNION 那么:
I think there are differences I'm overlooking but if you just want the post if it's in the first or second without using a UNION then: