这两个查询有什么区别?为何结果不同?

时间:2010-11-21 16:01:23

标签: mysql join count subquery

- 为total_classes

提供的值不正确
SELECT IFNULL(count(wc.id_wc),0) AS total_classes

FROM `all_tag_relations` AS a
    LEFT JOIN (tags AS t, WebClasses as wc) 
    ON ( a.id_tag = t.id_tag AND a.id_tutor = wc.id_author )
GROUP BY a.id_tutor

但是这个 - 带子查询会给出正确的值 -

SELECT (SELECT IFNULL(count(wc.id_wc),0) FROM WebClasses as wc WHERE wc.id_author = a.id_tutor) AS total_classes


FROM `all_tag_relations` AS a
     LEFT JOIN (tags AS t) ON ( a.id_tag = t.id_tag) 
group by a.id_tutor

解决方案 解决方案是将其他表与实际的Tutors表连接,使用All_Tag_relations,如此

...FROM Tutors as td on join All_Tag_Relations as a on td.id_tutor=a.id_tutor LEFT JOIN ...

1 个答案:

答案 0 :(得分:0)

您的查询都非常奇怪,并且不清楚您要执行的操作。也许您应该显示您的表并要求查询以检索您想要的数据。

这些查询之间的区别主要是第二个给出了WebClasses的总数,第二个给出了obCbClasses的数量乘以作者/导师的数量乘以标签数量,因为它们是不相交的并且那里是标签,WebClasses和all_tag_relations之间的所有1:n关系。