我有一个下载组件,希望类别提前显示子目录和项目数。两者中的 1 个有效,但当尝试同时获得两者时,结果是两者的乘积。
我使用的代码:
SELECT a.*,
count(b.parentid) AS catscount,
count(c.id) AS itemscount
FROM (jos_foc_downl_categories AS a LEFT JOIN jos_foc_downl_items AS c ON c.catid = a.id )
LEFT JOIN jos_foc_downl_categories AS b ON b.parentid = a.id
WHERE a.parentid=0
GROUP BY a.id
结果是一个类别有 4 个子类别和 5 个文件,其中 catscount 为 20 个,itemscount 为 20 个。
这是怎么回事?谢谢!
最佳答案
您正在计算所有行,包括重复值。使用 DISTINCT 只计算每个不同的值一次:
SELECT a.*,
count(DISTINCT b.parentid) AS catscount,
count(DISTINCT c.id) AS itemscount
....
关于mysql - 2 查询中的 LEFT JOINS 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4256982/