mysql连接多个表和计数查询

时间:2015-05-30 21:48:06

标签: mysql

我共有6张表,其中保存了不同的信息

现在我需要一个结果,从5个表中获取计数并从主表中选择所有信息,但如果记录不存在,则必须返回0而不是没有找到行,这就是问题

我尝试了以下查询,但未获得成功

SELECT 
    u.*,
    COUNT(DISTINCT  c.id) as comments,
    COUNT(DISTINCT d.id) as dislikes,
    COUNT(DISTINCT l.id) as likes,
    COUNT(DISTINCT s.id) as shares,
    COUNT(DISTINCT t.id) as tags
FROM 
    job_details as u
    JOIN job_comments as c ON u.id = c.job_id
    JOIN job_dislike as d ON u.id = d.job_id
    JOIN job_like as l ON u.id = l.job_id
    JOIN job_share as s ON u.id = s.job_id
    JOIN job_tags as t ON u.id = t.job_id
WHERE 
    u.id = c.job_id AND
    u.id = d.job_id AND
    u.id = l.job_id AND
    u.id = s.job_id AND
    u.id = t.job_id

GROUP BY 
    u.id

执行此查询,但未获得确切的结果。 我不太明白为什么。

我希望有人可以帮助我吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

使用LEFT JOIN代替JOIN。并且您不需要WHERE子句,因为您已加入这些表。并且,使用IFNULL函数为空值返回0。你需要像这样修改你的查询:

SELECT u.id,
    IFNULL(COUNT(DISTINCT  c.id),0) as comments,
    IFNULL(COUNT(DISTINCT d.id),0) as dislikes,
    IFNULL(COUNT(DISTINCT l.id),0) as likes,
    IFNULL(COUNT(DISTINCT s.id),0) as shares,
    IFNULL(COUNT(DISTINCT t.id),0) as tags
FROM job_details as u
    LEFT JOIN job_comments as c ON u.id = c.job_id
    LEFT JOIN job_dislike as d ON u.id = d.job_id
    LEFT JOIN job_like as l ON u.id = l.job_id
    LEFT JOIN job_share as s ON u.id = s.job_id
    LEFT JOIN job_tags as t ON u.id = t.job_id
GROUP BY u.id

答案 1 :(得分:1)

您可能没有得到确切的结果,因为某些表可能缺少值。

虽然您可以使用$(document).ready(function(){ $("body").on("click", ".slide", function(e){ e.preventDefault(); console.log($("#tam-content").load($(this).data("url") + ' ' + $(this).data("target"))); }); }); 解决此问题,但更安全的解决方案是预先汇总数据:

LEFT JOIN

为什么这样更好?考虑一个包含5条评论,喜欢,不喜欢,分享和标签的ID。 SELECT u.*, c.comments, d.dislikes, l.likes, s.shares, t.tags FROM job_details as u LEFT JOIN (select c.job_id, count(*) as comments from job_comments group by c.job_id ) c ON u.id = c.job_id LEFT JOIN (select d.job_id, count(*) as dislikes from job_dislike d group by d.job_id ) d ON u.id = d.job_id LEFT JOIN (select l.job_id, count(*) as likes from job_like l group by l.job_id ) l ON u.id = l.job_id LEFT JOIN (select s.job_id, count(*) as shares from job_share s group by s.job_id ) s ON u.id = s.job_id LEFT JOIN (select t.job_id, count(*) as tags from job_tags t group by t.job_id ) t ON u.id = t.job_id; 方法产生5 * 5 * 5 * 5 * 5 = 3,125中间行的中间结果。对于流行的ID来说,事情真的无法实现。