如何使用 INNER JOIN select,给出相关但不相关的记录
How to select with INNER JOIN, giving related but also unrelated records
我有这两个 tables:
用户
+----+-------+
| id | name |
+----+-------+
| 1 | John |
+----+-------+
| 2 | Peter |
+----+-------+
| 3 | Lucas |
+----+-------+
礼物
+----+--------+----------+----------+
| id | boy_id | type | quantity |
+----+--------+----------+----------+
| 1 | 1 | clothing | 3 |
+----+--------+----------+----------+
| 2 | 2 | toy | 1 |
+----+--------+----------+----------+
| 3 | 2 | clothing | 2 |
+----+--------+----------+----------+
我正在尝试查询“男孩收到的礼物”,类似这样:
+-------+----------+----------+
| name | type | quantity |
+-------+----------+----------+
| John | clothing | 3 |
+-------+----------+----------+
| Peter | toy | 1 |
+-------+----------+----------+
| Peter | clothing | 2 |
+-------+----------+----------+
| Lucas | "" | 0 |
+-------+----------+----------+
但我只知道如何通过这样的查询获取相关数据:
SELECT u.name, g.type, g.quantity FROM gifts g INNER JOIN users u ON g.boy_id = u.id
因此,由于 Lucas 不在 gifts table 中,我得到以下信息:
+-------+----------+----------+
| name | type | quantity |
+-------+----------+----------+
| John | clothing | 3 |
+-------+----------+----------+
| Peter | toy | 1 |
+-------+----------+----------+
| Peter | clothing | 2 |
+-------+----------+----------+
那么,如何将 peter 添加到结果中,用“”填充类型和数量,如果男孩没有收到礼物则为零?
你可以 left join
:
SELECT u.name, g.type, COALESCE(g.quantity, 0) quantity
FROM users u
LEFT JOIN gifts g ON g.boy_id = u.id
我有这两个 tables:
用户
+----+-------+
| id | name |
+----+-------+
| 1 | John |
+----+-------+
| 2 | Peter |
+----+-------+
| 3 | Lucas |
+----+-------+
礼物
+----+--------+----------+----------+
| id | boy_id | type | quantity |
+----+--------+----------+----------+
| 1 | 1 | clothing | 3 |
+----+--------+----------+----------+
| 2 | 2 | toy | 1 |
+----+--------+----------+----------+
| 3 | 2 | clothing | 2 |
+----+--------+----------+----------+
我正在尝试查询“男孩收到的礼物”,类似这样:
+-------+----------+----------+
| name | type | quantity |
+-------+----------+----------+
| John | clothing | 3 |
+-------+----------+----------+
| Peter | toy | 1 |
+-------+----------+----------+
| Peter | clothing | 2 |
+-------+----------+----------+
| Lucas | "" | 0 |
+-------+----------+----------+
但我只知道如何通过这样的查询获取相关数据:
SELECT u.name, g.type, g.quantity FROM gifts g INNER JOIN users u ON g.boy_id = u.id
因此,由于 Lucas 不在 gifts table 中,我得到以下信息:
+-------+----------+----------+
| name | type | quantity |
+-------+----------+----------+
| John | clothing | 3 |
+-------+----------+----------+
| Peter | toy | 1 |
+-------+----------+----------+
| Peter | clothing | 2 |
+-------+----------+----------+
那么,如何将 peter 添加到结果中,用“”填充类型和数量,如果男孩没有收到礼物则为零?
你可以 left join
:
SELECT u.name, g.type, COALESCE(g.quantity, 0) quantity
FROM users u
LEFT JOIN gifts g ON g.boy_id = u.id