2016-11-25 97 views
0

我有如下表:MySQL的三重连接查询

users table 
user_id user_email user_name 
    1  [email protected]  a 
    2  [email protected]  b 
    3  [email protected]  c 

    bookmarks table 
bookmark_id user_id  bookmark_url 
    1   1  http://aaa.com 
    2   3  http://bbb.com 
    3   3  http://ccc.com 
    4   3  http://ddd.com 

    comments table 
comment_id user_id  content 
    1   2   'hello' 
    2   2   'hello2' 

我想是这样的:

user_id user_email user_name bookmarksCount commentsCount 
    1  [email protected]  a   1    0 
    2  [email protected]  b   0    2 
    3  [email protected]  c   3    0 

从以上,每个xxx_id是自动递增的序列号。

我想要得到以上结果,我必须加入这3个表。但是,如果在书签和评论表中没有匹配user_id,则它们不能加入。但是如果没有匹配,我必须得到结果0

即使没有匹配列,是否可以连接这些表以获得结果?

+0

难以处理连接(即使是左连接),因为您希望在同一查询中有两个单独的计数,因此有效地实现了两个单独的聚合函数。如下建议的单独查询/子查询是一个体面的解决方案 – ADyson

回答

3

你可以使用相关子查询:

select u.*, 
     (select count(*) from bookmarks bm where bm.user_id = u.user_id 
     ) as cnt_bookmarks, 
     (select count(*) from comments c where c.user_id = u.user_id 
     ) as cnt_comments 
from users u; 

如果试图做到这一点使用join,你将有问题的,因为你会产生书签和注释为每个用户的笛卡尔乘积。另外,在连接之后进行聚合很可能会导致性能问题,因为聚合的数据将大于必要的数据。

对于此查询,bookmarks(user_id)comments(user_id)上的索引应提供非常好的性能。