如何组合这三个查询?

时间:2010-08-15 06:06:17

标签: mysql join left-join

我需要使用连接将三个MySQL查询合并到一个查询中。我在弄清楚如何做到这一点时遇到了很多麻烦。以下是三个查询。

select 
    sum(A.a) 
from A join B 
on A.BID = B.id 
where B.userID=userID

select 
    sum(C.c)
from D left join (C) 
on (D.id=C.DID)
 where D.userID = userID

select sum(E.e) from E where E.userID=userID

我需要以某种方式将所有这些查询组合到与用户表连接的单个查询中,以便为每个user.id提供sum(A.a)+sum(C.C)+sum(E.e)。我在所有表格中尝试了左连接

user left join (A, B, C, D, E)
on ((A.BID = B.id and B.userID=user.id) 
    or (D.id=C.DID and D.userID = user.id) 
    or (E.userID=user.id))

在黑暗中它几乎是一个镜头,它失败了。我不知道如何结合这三个查询,有人给我一个提示吗?

编辑以澄清:我需要将此查询作为用户表与上述查询的连接,因为我需要能够选择sum_value排序的所有用户ID。之前的三个查询是单独运行的,并使用单个userID进行参数化。

进一步编辑:尝试联盟的所有变种都加入了我可以想到的用户查询,但它不起作用。它非常接近于使用一些调整,但它仍然返回不正确的值。我不确定为什么这样做。

2 个答案:

答案 0 :(得分:3)

可能是这样的:

select sum(sum_value), user_id from (
select 
    sum(A.a) as sum_value, B.userID as user_id
from A join B 
on A.BID = B.id 
GROUP BY B.userID

UNION ALL

select 
    sum(C.c) as sum_value, D.userID as user_id
from D left join (C) 
on (D.id=C.DID)
GROUP BY D.userID

UNION ALL

select sum(E.e) as sum_value, E.userID as user_id from E
GROUP BY E.userID
)
GROUP BY user_id

答案 1 :(得分:2)

select 
   ( ( select 
        sum(A.a)
    from 
        A join B 
        on A.BID = B.id 
    where 
        B.userID = user.ID ) + 
    ( select 
          sum(C.c)
      from 
          D left join (C) 
          on (D.id = C.DID)
     where D.userID = user.ID ) +
    ( select
          sum(E.e)
      from 
          E 
      where 
          E.userID = user.ID ) )
from
    user