具有2个连接和计数的SQL查询

时间:2014-07-27 08:14:53

标签: sql join count

我花了最后8个小时试图让这个SQL查询工作,我无法完成它。我不是很有经验,但我正努力做得更好。

我有两张桌子:

Table giveaway
Columns:
id | userid | created | closed | winnerid | cancelled
1 | 7962290564 | 2014-07-26 20:32:22 | 2014-07-26 20:32:22 | 7962290566 | NULL
2 | 7962290565 | 2014-07-26 20:32:22 | 2014-07-26 20:32:22 | 7962290567 | NULL
3 | 7962290566 | 2014-07-26 20:32:22 | 2014-07-26 20:32:22 | 7962290567 | NULL
4 | 7962290566 | 2014-07-26 20:32:22 | 0000-00-00 00:00:00 | NULL | NULL

Table user
Columns:
id | steamid | joined | roleid | name 
1 | 7962290564 | 2014-07-26 20:32:22 | 1 | User a
2 | 7962290565 | 2014-07-26 20:32:22 | 4 | User b
3 | 7962290566 | 2014-07-26 20:32:22 | 4 | User c
4 | 7962290567 | 2014-07-26 20:32:22 | 4 | User d
5 | 7962290568 | 2014-07-26 20:32:22 | 4 | User e
6 | 7962290569 | 2014-07-26 20:32:22 | 5 | User f

我所追求的是一个结果,它会计算一个人在giveaway.userid中拥有自己身份的次数以及有人在giveaway.winnerid中拥有自己身份的次数。 此外,它还有一些WHERE元素可以过滤掉不需要的结果。

它类似于:

SELECT user.steamid, user.name, count(giveaway.userid) nrgiven, count(giveaway.winnerid) nrwon
FROM user
WHERE user.roleid BETWEEN 1 AND 4
AND giveaway.cancelled IS NULL    
AND giveaway.closed IS NOT NULL
GROUP BY user.steamid

For these tables user.steamid = giveaway.userid
                 user.steamid = giveaway.winnerid

结果应为:

steamid | name | nrwon | nrgiven
7962290564 | User a | 0 | 1
7962290565 | User b | 0 | 1
7962290566 | User c | 1 | 2
7962290567 | User d | 2 | 0
7962290568 | User e | 0 | 0

以下是我尝试过的一些例子,但没有一个做得好。

SELECT user.steamid, user.name, count(giveaway.userid) nrgiven
FROM user
INNER JOIN giveaway
    ON user.steamid = giveaway.userid
    AND user.roleid BETWEEN 1 AND 4
    AND giveaway.closed IS NOT NULL
    AND giveaway.cancelled IS NULL
GROUP by user.steamid
ORDER BY nrgiven DESC;

---

SELECT user.roleid, user.steamid, user.name, a.nrgiven, b.nrwon 
FROM user, 
    ( SELECT count(user.steamid) nrgiven
    FROM user
    LEFT JOIN giveaway ON user.steamid = giveaway.userid 
    ) a,
    ( SELECT count(user.steamid) nrwon
    FROM user
    LEFT JOIN giveaway ON user.steamid = giveaway.winnerid 
    ) b;

---

SELECT user.steamid, user.name, a.nrwon
FROM user,
( SELECT count(giveaway.winnerid) nrwon
    FROM giveaway
    RIGHT JOIN user ON giveaway.winnerid = user.steamid
    WHERE user.roleid BETWEEN 1 AND 4
        AND giveaway.closed != 0
        AND giveaway.winnerid IS NOT NULL
    GROUP BY user.steamid

) a
GROUP BY user.steamid
ORDER BY steamid DESC;

1 个答案:

答案 0 :(得分:1)

我能够使用以下查询从该数据集中获取您的预期结果表:

SELECT user.steamid, user.name, COALESCE(winners.nrwon,0) as nrwon, COALESCE(nrgiveaways.nrgiven,0) as nrgiven
FROM user
LEFT JOIN (SELECT winnerid, COUNT(*) as nrwon FROM giveaway WHERE winnerid IS NOT NULL GROUP BY winnerid) as winners on winners.winnerid = user.steamid
LEFT JOIN (SELECT userid, COUNT(*) as nrgiven FROM giveaway GROUP BY userid) as nrgiveaways on nrgiveaways.userid = user.steamid
WHERE roleid in (1,2,3,4)

获奖者和赠品可以在他们自己的表中找到,然后使用左连接添加到用户表中。