如何将这两个复杂的查询组合成一个没有联合的查询?

时间:2011-10-23 00:03:51

标签: sql join union

(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)

很明显,两个查询中的最后一个连接是相同的。只是不确定如何“或”一起加入。

3 个答案:

答案 0 :(得分:2)

有些联盟似乎多余:

  • discussions可以直接在subscriptions列加入company_id;

  • posts可以直接在subscriptions列加入analyst_id;

  • SELECT中的最后一次加入users是不必要的,因为没有从该表中检索数据,过滤器(users.id = 6)可以重新应用于subscriptions.user_id

所以,我可能会重写这样的查询:

SELECT p.id
FROM posts p
  INNER JOIN discussions d ON d.post_id = p.id
  INNER JOIN subscription s
    ON s.subscribable_type = 'Company' AND s.subscribable_id = d.company_id
    OR s.subscribable_type = 'User'    AND s.subscribable_id = p.analyst_id
WHERE s.user_id = 6

答案 1 :(得分:1)

这是未经测试的,但请尝试一下。如果有效,请告诉我。

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.subcribable_id = companies.id
inner join users
on subscriptions.user_id = users.id
or users.id = posts.analysis_id
where subscriptions.subscribable_type in ('Company', 'User')
and users.id = 6

答案 2 :(得分:0)

我认为我有一些不同之处,但如果您只是想要帖子,如果它在第一次或第二次没有使用UNION那么:

SELECT posts.id FROM posts
where posts.id IN 
(
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
)
or
posts.id IN 
(
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
)