使用分组依据加入三个表来获取计数

时间:2016-07-26 01:31:08

标签: mysql group-by left-join

我有三个表 - 广告(Id,AgentId,AdDesc,AdTitle,EmailId,ADate),AdComment(ComId,电子邮件,评论,AdId)和MyLikes(LikeId,电子邮件,AdId)。在这里,我必须加入三个表格并根据每个广告ID(Ad.Id = AdComment.AdId)显示广告表的所有字段以及来自AdComment表的评论数量,以及基于每个广告ID的给定电子邮件来自MyLikes的喜欢的数量(Ad.Id = MyLikes.AdId)。

当我刚加入广告和广告评论时,我使用了

SELECT * , (
SELECT COUNT( c.AdId )
) AS ComCount
FROM Ad a
LEFT JOIN AdComment c ON a.Id = c.AdId 
GROUP BY a.Id
ORDER BY a.Id DESC

这很好。

当我加入Ad和MyLikes时,我使用了 -

SELECT a.Id, (
SELECT COUNT( * )
FROM MyLikes m
WHERE (
m.email = 'nik@gmail.com'
AND m.AdId = a.Id
)
) AS MyCount
FROM Ad a
LEFT JOIN MyLikes m ON a.Id = m.AdId
GROUP BY a.Id

这很好。

但是,当我尝试所有三个表连接时它不起作用,给评论计数提供了一些错误的值。 为此,我用 -

SELECT a.Id,a.AgentId,a.EmailId,a.AdTitle,a.AdDesc, (
SELECT COUNT(m.AdId)
FROM MyLikes m
WHERE (
m.email = 'nik@gmail.com'
AND m.AdId = a.Id
)
) AS MyCount,(
SELECT COUNT( c.AdId )
) AS ComCount
FROM Ad a
LEFT JOIN MyLikes m ON a.Id = m.AdId LEFT JOIN AdComment c ON a.Id = c.AdId
GROUP BY a.Id ORDER BY a.Id DESC    

如何加入这三个表并获得所需的结果。

2 个答案:

答案 0 :(得分:0)

假设我正确理解了您的问题,可以使用子查询来count代替joins中的数据:

select a.Id, a.AgentId, a.EmailId, a.AdTitle, a.AdDesc, 
       b.AdIdCount, c.AdIdCount
from Ad a
       left join (select AdId, count(*) AdIdCount 
                  from AdComment 
                  group by AdId) b ON a.Id = b.AdId 
       left join (select AdId, count(*) AdIdCount 
                  from MyLikes 
                  where email = 'nik@gmail.com'
                  group by AdId) c ON a.Id = c.AdId 

如果您更喜欢correlated subqueries,那么这应该有效:

select a.Id, a.AgentId, a.EmailId, a.AdTitle, a.AdDesc, 
       (select count(*) 
        from AdComment b 
        where a.Id = b.AdId),
       (select count(*) 
        from MyLikes c 
        where c.email = 'nik@gmail.com' and 
            a.Id = c.AdId)
from Ad a

答案 1 :(得分:0)

假设LikeID和ComId是MyLikes和AdComment表的唯一ID字段,那么您应该能够使用一对连接并计算每个表中的不同id字段: -

SELECT a.Id,
        a.AgentId,
        a.EmailId,
        a.AdTitle,
        a.AdDesc,
        COUNT(DISTINCT m.LikeId) AS MyCount,
        COUNT(DISTINCT c.ComId) AS ComCount
FROM Ad a
LEFT OUTER JOIN MyLikes m ON m.email = 'nik@gmail.com' AND a.Id = m.AdId
LEFT JOIN AdComment c ON a.Id = c.AdId