我有3张桌子:
播放器:
精细:
Committee_member :
所以我想得到的输出是;名称,缩写,金额。但我只想看到一些罚款的球员也是委员会成员。我试过这个:
SELECT name, initials, amount
FROM Player
JOIN Fine on Player.playernumber = Fine.playernumber
JOIN Committee_member on Player.playernumber = Comittee_member.playernumber
这给了我所有有罚款的成员,也是委员会成员,但它给了我双重输出,这是不正确的。有谁知道我能做什么,所以我没有得到双倍的输出?
感谢网站上的人们,我发现WHERE EXISTS (...)
可以解决我的问题:
SELECT name, initials, amount
FROM Player
JOIN Fine on Player.playernumber = Fine.playernumber
WHERE EXISTS (SELECT *
FROM Committee_member
WHERE Player.playernumber = Comittee_member.playernumber)
您可以做的另一件事是计算每个委员会成员的罚款金额:
SELECT name, initials, COUNT(amount) as 'amount'
FROM Player
JOIN Fine on Player.playernumber = Fine.playernumber
WHERE Player.playernumber IN (SELECT playernumber from Committee_member)
GROUP BY name, initials
答案 0 :(得分:2)
我的猜测是,玩家可以在一个以上的委员会或者有一个以上的罚款。因此,请使用group by
:
SELECT p.name, p.initials, SUM(f.amount) as total_fines
FROM Player JOIN Fine
ON p.playernumber = f.playernumber JOIN
Committee_member cm
ON p.playernumber = cm.playernumber
GROUP BY p.name, p.initials;
答案 1 :(得分:0)
这是另一个较短的选择:
SELECT name, initials, amount
FROM Player
JOIN Fine on Player.playernumber = Fine.playernumber
WHERE Player.playernumber IN (SELECT playernumber FROM Committee_member)
答案 2 :(得分:-1)
您可以使用GROUP BY语句来获取唯一结果。请参阅the MySQL docs。