我有两张 table 。一个保存所有可用的奖杯,一个保存用户和奖杯之间的关系。
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 |
------------------------------------------
例如 用户 1 赢得了杀死 100 人和杀死 200 人的奖杯。
我想要一个显示如下内容的查询:
for user 1
-----------------------------
| kill 100 people | 1 |
| kill 200 people | 1 |
| fly 5000 feet upwards | 0 |
| fly into a mountain | 0 |
-----------------------------
这是我试过的:
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
但我只得到用户得到的结果,我想要 temp = 0 行。 是否可以在一个查询中执行此操作?
最佳答案
要使左连接生效,您需要将条件 earned_trophys.user_id = 1
移动到 on
子句中,而不是 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
关于MySQL加入并获取所有关系,即使为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656483/