MySQL加入并获得所有关系,即使0

Emi*_*mil 4 mysql join

我有两张桌子.一个拥有所有可用的奖杯,另一个拥有用户和奖杯之间的关系.

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       |
------------------------------------------
Run Code Online (Sandbox Code Playgroud)

例如,用户1已经杀死100人并杀死200人的奖杯.

我想要一个查询,向我显示这样的事情:

for user 1
-----------------------------
| kill 100 people       | 1 |
| kill 200 people       | 1 |
| fly 5000 feet upwards | 0 |
| fly into a mountain   | 0 |
-----------------------------
Run Code Online (Sandbox Code Playgroud)

这是我试过的:

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
Run Code Online (Sandbox Code Playgroud)

但我只得到用户得到的东西的结果,我想要temp = 0行.是否可以在一个查询中执行此操作?

Imr*_*e L 7

要使左连接生效,您需要将条件移动earned_trophys.user_id = 1on子句中而不是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
Run Code Online (Sandbox Code Playgroud)

  • 惊人的!非常感谢! (2认同)