Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Join and get all relations even if 0

Tags:

join

mysql

I got two tables. One that holds all availeble trophys and one that holds the relation between user and trophy.

trophy
--------------------------------------
| trophy_id | name                   |
--------------------------------------
| 1         | kill 100 people        |
| 2         | kill 200 people        |
| 3         | fly 5000 feet upwards  |
| 4         | fly into a mountain    |
--------------------------------------

earned_trophys
------------------------------------------
| earned_trophy_id | trophy_id | user_id |
------------------------------------------
| 1                | 1         | 3       |
| 2                | 1         | 2       |
| 3                | 3         | 4       |
| 4                | 2         | 1       |
| 5                | 3         | 1       |
------------------------------------------

For example User 1 has earned the kill 100 people and kill 200 people trophys.

I want a query that shows me something like this:

for user 1
-----------------------------
| kill 100 people       | 1 |
| kill 200 people       | 1 |
| fly 5000 feet upwards | 0 |
| fly into a mountain   | 0 |
-----------------------------

this is what I have tried:

select
    trophy.name,
    earned_trophys.user_id,  
    count(user_id) as temp
from
    trophy
left join
    earned_trophys
on
    trophy.trophy_id = earned_trophys.trophy_id
where
    earned_trophys.user_id = 1
group by
    name

but I only get the results for the things the user got, I want the temp = 0 rows to. is it possible to do this in one query?

like image 243
Emil Avatar asked Feb 27 '23 07:02

Emil


1 Answers

for left join to be in effect you need to move condition earned_trophys.user_id = 1 into the on clause instead of where.

select
    trophy.name,
    earned_trophys.user_id,  
    count(user_id) as temp
from
    trophy
left join
    earned_trophys
on
    trophy.trophy_id = earned_trophys.trophy_id and earned_trophys.user_id = 1
group by
    name
like image 84
Imre L Avatar answered Mar 12 '23 11:03

Imre L