尝试根据前一个表中的选择从两个不同的表中获取多个COUNT(id)

时间:2012-03-05 22:26:16

标签: php mysql

我正在尝试获取特定成员的所有'krits',并获得COUNT(id)来自其他2个表的kritID行数。

这是我到目前为止所得到的,但它没有得到准确的数字似乎已经相互添加了计数。在每个返回的kritID中。

是否可以通过单个SQL查询为每个查询获得单独的计数?

SELECT  krit.id, krit.short_url, COUNT(referring_url) AS views , COUNT(click_date) AS clicks

FROM ukritic_krits AS krit
LEFT JOIN ukritic_krits_stats AS views ON views.kritID = krit.id
LEFT JOIN ukritic_links_out AS clicks ON clicks.kritID = krit.id

WHERE (krit.memberID = '[LOGGED IN MEMBER ID]')

GROUP BY krit.id

P.S。一些返回的计数我是0,但我仍然需要在结果行中返回的值

2 个答案:

答案 0 :(得分:2)

尝试使用COUNT(DISTINCT)

SELECT 
    krit.id, krit.short_url, 
    COUNT(DISTINCT views.id) AS views, 
    COUNT(DISTINCT click.id) AS clicks
FROM ukritic_krits AS krit
LEFT JOIN ukritic_krits_stats AS views ON views.kritID = krit.id
LEFT JOIN ukritic_krits_stats AS clicks ON clicks.kritID = krit.id
WHERE (krit.memberID = '[LOGGED IN MEMBER ID]')
GROUP BY krit.id

我的猜测是,您看到的问题是,总计数将等于views的数量乘以clicks的数量,因为每个匹配的view记录都是每个匹配的left joined记录clicks。通过执行COUNT(DISTINCT),您只需计算每个唯一ID而不是所有行。


修改

您问题中的查询已更改,因此我必须进行编辑,在这种情况下使用子选项而不是LEFT JOINs可能更有效,因为您可以避免不同的操作......但是你当然应该测试一下:

SELECT  
    krit.id, 
    krit.short_url, 
    (SELECT COUNT(*) FROM ukritic_krits_stats WHERE kritID = krit.id) AS views, 
    (SELECT COUNT(*) FROM ukritic_links_out WHERE kritID = krit.id) AS clicks
FROM ukritic_krits AS krit
WHERE (krit.memberID = '[LOGGED IN MEMBER ID]')

答案 1 :(得分:0)

SELECT krit.id, krit.short_url, 
       SUM(CASE WHEN views.id IS NOT NULL THEN 1 ELSE 0 END) AS views, 
       SUM(CASE WHEN click.id IS NOT NULL THEN 1 ELSE 0 END) AS clicks    
    FROM ukritic_krits AS krit
        LEFT JOIN ukritic_krits_stats AS views 
            ON views.kritID = krit.id
        LEFT JOIN ukritic_krits_stats AS clicks 
            ON clicks.kritID = krit.id    
    WHERE (krit.memberID = '[LOGGED IN MEMBER ID]')    
    GROUP BY krit.id