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

时间:2010-09-07 07:13:12

标签: 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       |
------------------------------------------

例如 用户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行。 是否可以在一个查询中执行此操作?

1 个答案:

答案 0 :(得分:7)

要使左连接生效,您需要将条件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