sql - 从多个连接表中获取匹配行的计数

时间:2014-10-24 12:07:08

标签: mysql sql

我正在尝试获取属于我的“广告”表(也属于用户)中各行的点击次数和观看次数。我也试图通过观看次数最多的广告来订购结果。

我的桌子结构:

用户:

id name
1  James

广告:属于用户(FK:user_id)

id user_id
22 1
23 4

观看次数:属于广告(FK:ad_id)

id ad_id
1  22
2  22
3  23

点击次数:属于广告(FK:ad_id)

id ad_id
1  22
2  22
3  23

从上表中,我想要一个结果,其中包含属于id = 1的用户的所有广告的数据以及每个广告的点击和查看次数

id user_id clicks_count views_count
22 1       2            2

这是我到目前为止所拥有的。使用此SQL,我只获得一个/第一个“广告”行的正确数量的观看次数和点击次数,但忽略其他匹配的行。

SELECT ads.id, COUNT(DISTINCT views.id) AS view_count, COUNT(DISTINCT clicks.id) AS click_count   
FROM users
INNER JOIN ads ON ads.`user_id` = users.`id`
INNER JOIN views ON ads.id = views.`ad_id`
INNER JOIN clicks ON ads.id = clicks.`ad_id`
WHERE users.`id` = 1
GROUP BY views.`ad_id`
ORDER BY `view_count` DESC

这是一个sqlfiddle http://sqlfiddle.com/#!2/5c43c/1/0

提前致谢

2 个答案:

答案 0 :(得分:2)

您需要使用LEFT OUTER JOIN才能丢失没有点击次数的广告

SELECT ads.id, COUNT(DISTINCT views.id) AS view_count, COUNT(DISTINCT clicks.id) AS click_count   
    FROM users
    INNER JOIN ads ON ads.`user_id` = users.`id`
    LEFT JOIN views ON ads.id = views.`ad_id`
    LEFT JOIN clicks ON ads.id = clicks.`ad_id`
    WHERE users.`id` = 1
    GROUP BY ads.`id`
    ORDER BY `view_count` DESC

答案 1 :(得分:2)

SELECT ads.id,ads.user_id, COUNT(DISTINCT views.id) AS view_count, 
COUNT(DISTINCT clicks.id) AS click_count   
    FROM users
    inner JOIN ads ON ads.`user_id` = users.`id`
    LEFT JOIN views ON ads.id = views.`ad_id`
    LEFT JOIN clicks ON ads.id = clicks.`ad_id`
    WHERE users.`id` = 1
    GROUP BY views.`ad_id`
    ORDER BY `view_count` DESC

INNER是正确的,但你应该使用两个左连接