从多个表中选择计数的奇怪问题(带连接)

时间:2011-05-04 12:24:46

标签: mysql join count

我对以下查询有一个奇怪的问题,它的工作正常, 其中的计数部分获取给定'hintout'

的评论数量

我正在尝试添加类似的计数,以获取每个提示的“投票”数量,以下是查询:

SELECT h.*
  , h.permalink AS hintout_permalink
  , hi.hinter_name
  , hi.permalink
  , hf.user_id AS followed_hid
  , ci.city_id, ci.city_name, co.country_id, co.country_name, ht.thank_id
  , COUNT(hc.comment_id) AS commentsCount 
FROM hintouts AS h 
INNER JOIN hinter_follows AS hf ON h.hinter_id = hf.hinter_id 
INNER JOIN hinters AS hi ON h.hinter_id = hi.hinter_id 
LEFT JOIN cities AS ci ON h.city_id = ci.city_id 
LEFT JOIN countries as co ON h.country_id = co.country_id 
LEFT JOIN hintout_thanks AS ht ON (h.hintout_id = ht.hintout_id 
  AND ht.thanker_user_id = 1)
LEFT JOIN hintout_comments AS hc ON hc.hintout_id = h.hintout_id 
WHERE hf.user_id = 1 
GROUP BY h.hintout_id 

我尝试将以下内容添加到选择部分:

COUNT(ht2.thanks_id) AS thanksCount 

以及关于加入的以下内容:

LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id

但发生了奇怪的事情,我找不到任何答案或解决方案, 就是在我添加这个附加部分的那一刻,评论的计数被毁了(我得错了和奇怪的数字),我得到相同的号码谢谢 - 我无法理解为什么或如何解决它......我避免使用嵌套查询

所以任何帮助或指示都将不胜感激!

ps:这可能已发布两次,但我找不到上一篇文章

2 个答案:

答案 0 :(得分:2)

添加

LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id

行数增加,您获得表hc的重复行,这些行在COUNT(hc.comment_id)中计为两倍。 你可以替换

COUNT(hc.comment_id) <<-- counts duplicated
/*with*/ 
COUNT(DISTINCT(hc.comment_id))  <<-- only counts unique ids

仅计算身份证上的独特外观。

对于不唯一的值,例如co.county_namecount(distinct将不起作用,因为它只会列出不同的国家/地区(如果您的所有结果都在美国,则计数将为1)。

<强> Quassnoi
通过将计数放在子选择中来解决整个计数问题,以便由所有这些连接引起的额外行不会影响这些计数。

答案 1 :(得分:1)

SELECT  h.*, h.permalink AS hintout_permalink, hi.hinter_name,
        hi.permalink, hf.user_id AS followed_hid,
        ci.city_id, ci.city_name, co.country_id, co.country_name,
        ht.thank_id,
        COALESCE(
        (
        SELECT  COUNT(*)
        FROM    hintout_comments hci
        WHERE   hc.hintout_id = h.hintout_id
        ), 0) AS commentsCount,
        COALESCE(
        (
        SELECT  COUNT(*)
        FROM    hintout_comments hti
        WHERE   hti.hintout_id = h.hintout_id
        ), 0) AS thanksCount
FROM    hintouts AS h 
JOIN    hinter_follows AS hf
ON      hf.hinter_id = h.hinter_id
JOIN    hinters AS hi
ON      hi.hinter_id = h.hinter_id
LEFT JOIN
        cities AS ci
ON      ci.city_id = h.city_id
LEFT JOIN
        countries as co
ON      co.country_id = h.country_id
LEFT JOIN
        hintout_thanks AS ht
ON      ht.hintout_id = h.hintout_id
        AND ht.thanker_user_id=1 
WHERE   hf.user_id = 1 
相关问题