(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.
Some joins seem redundant:
discussionscould be joined tosubscriptionsdirectly on thecompany_idcolumn;postscould be joined tosubscriptionsdirectly on theanalyst_idcolumn;the last join to
usersin 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: