添加另一个子查询

时间:2013-01-15 22:58:42

标签: mysql

我将此查询作为我的主查询,我使用成员表中的所有记录,并从comments和chat_box中选择列。

SELECT members.*, 
       a.commenter_id, 
       b.user_id, 
       a.comcount, 
       b.chatcount 
FROM   members 
       LEFT JOIN (SELECT commenter_id, 
                         Count(*) comCount 
                  FROM   comments 
                  GROUP  BY commenter_id) a 
              ON members.id = a.commenter_id 
       LEFT JOIN (SELECT user_id, 
                         Count(*) chatCount 
                  FROM   chat_box 
                  GROUP  BY user_id) b 
              ON members.id = b.user_id 
WHERE  members.id = '290' 

我想将此查询添加到上面的

SELECT Count(friend_id) AS totFriend, 
       friend_id        AS fi, 
       logged_user_id   AS user, 
       friend_accepted  AS fa 
FROM   member_friends 
WHERE  logged_user_id = '1' 
       AND friend_id = '290' 

是否可以将其添加到混音中而不会导致任何错误?我自己尝试过,但我可能只是把自己置于更深层次的问题中。如果有可能有人帮助我这样做,谢谢你:)。

1 个答案:

答案 0 :(得分:0)

如果您有办法将最后一个查询加入members表,那么您应该可以使用:

SELECT members.*, 
  a.commenter_id, 
  b.user_id, 
  a.comcount, 
  b.chatcount,
  c.totFriend
FROM   members 
LEFT JOIN 
(
  SELECT commenter_id, 
    Count(*) comCount 
  FROM   comments 
  GROUP  BY commenter_id
) a 
  ON members.id = a.commenter_id 
LEFT JOIN 
(
  SELECT user_id, 
    Count(*) chatCount 
  FROM   chat_box 
  GROUP  BY user_id
) b 
 ON members.id = b.user_id 
LEFT JOIN
(
  SELECT Count(friend_id) AS totFriend, 
       friend_id        AS fi, 
       logged_user_id   AS user, 
       friend_accepted  AS fa 
  FROM   member_friends 
  WHERE  logged_user_id = '1' 
   AND friend_id = '290'
) c
  on members.id = c.friend_id
WHERE  members.id = '290'