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

标签 mysql join

我有两张 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/

相关文章:

sql - 关于从mysql中的表中删除数据库数据

sql - 连接多个表(多对多关系)

java - Hibernate Criteria 多表

MYSQL - 错误 1215 (HY000) : Cannot add foreign key constraint

php - CKEditor 输出为 BBcode 格式而不是 HTML

mysql - MySQL 中的联接用于获取多个表数据

mysql - 如何从 SQL 行中的列中删除特定值?

Mysql join 每次匹配得到一行

MySQL更新表以填充另一个表中的空值

MySQL查询求和另一个表中的值