计算2列以进行发生

时间:2015-07-02 03:54:25

标签: mysql sql innodb

基本上,我需要一个能够返回显示名称,杀人数量和死亡人数的查询。

我需要提供两张桌子。

这两个表是

player

id      | name
2334324 | user
4353454 | user2

其中id是其唯一标识符,name是其显示名称。

第二个表是:

player_kill

id | killer  | victim  |
1  | 2334324 | 4353454 |
2  | 2334324 | 4353454 |  
3  | 4353454 | 2334324 |

其中killer / victim列包含player表的唯一标识符。

我希望能够计算killervictim中玩家ID的出现次数,以便查询返回:

name | kills | deaths
user | 2     | 1
user2| 1     | 2

其中被杀数为playeridkiller中出现的数量与死亡人数相同

希望我提供了足够的信息。

到目前为止我所拥有的:

SELECT `player`.`name`, COUNT(DISTINCT `player_kill`.`id`) as `kills`, COUNT(DISTINCT `player_kill`.`id`) as `deaths`
FROM `player`
LEFT JOIN `player_kill` ON `player`.`id`=`player_kill`.`killer`
LEFT JOIN `player_kill` ON `player`.`id`=`player_kill`.`victim`
WHERE `player`.`id` = `player_kill`.`killer` AND `player`.`id` = `player_kill`.`victim`
GROUP BY `player`.`id`;

2 个答案:

答案 0 :(得分:3)

尝试

SELECT 
    p.name, 
    count(distinct pk1.id) as kills, 
    count(distinct pk2.id) as deaths
FROM player p
LEFT JOIN player_kill pk1 ON pk1.killer = p.id 
LEFT JOIN player_kill pk2 ON pk2.victim = p.id 
group by p.name

http://sqlfiddle.com/#!9/649504/15/0

答案 1 :(得分:3)

看看是否有效:

SELECT  `player`.`name`,
        COUNT(DISTINCT k.`id`) as `kills`,
        COUNT(DISTINCT v.`id`) as `deaths`
    FROM  `player`
    LEFT JOIN  `player_kill` AS k ON `player`.`id` = k.`killer`
    LEFT JOIN  `player_kill` AS v ON `player`.`id` = v.`victim`
    GROUP BY  `player`.`id`;

如果没有,那么我们可能需要将COUNT转换为子查询。