Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count 2 columns for occurrence

Tags:

sql

mysql

innodb

So basically, I require a query that will return display name, amount of kills and amount of deaths.

I have two tables that I need to pull from.

The two tables are

player

id      | name
2334324 | user
4353454 | user2

where id is their unique identifier and name is their display name.

The second table is:

player_kill

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

where killer / victim columns contain the unique identifier of the player table.

I'd like to be able to count the occurrences of player id in the killer and victim so that the query returns:

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

where the number under kills would be the amount of occurrences the playerid has in the killer column and same for deaths

Hope I provided enough information.

What I have so far:

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`;
like image 563
Jacob Avatar asked Dec 05 '25 05:12

Jacob


2 Answers

Try

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

like image 70
Dewanta Avatar answered Dec 07 '25 20:12

Dewanta


See if this works:

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`;

If not, then we may need to make the COUNTs into subqueries.

like image 21
Rick James Avatar answered Dec 07 '25 22:12

Rick James