我有两个表,我想查询2个表以获得报告。
POSITION
+-------------+---------------+
| position_id | position_name |
+-------------+---------------+
| 1 | E1P1 |
| 2 | E1P2 |
| 3 | E3P3 |
| 4 | E4P4 |
+-------------+---------------+
PEOPLE
+------------+-------------+--------------------+
| people_id | people_name | people_position_id |
+------------+-------------+--------------------+
| 1 | JOHN | 2 |
| 2 | MARK | 4 |
+------------+-------------+--------------------+
查询
SELECT position_id, position_name, people_name FROM position
RIGHT JOIN people ON people_position_id = position_id
当我使用简单查询时,我只会得到匹配的行,如何获得全部?
我想获得此结果
+----+----------+--------+
| ID | POSITION | STATUS |
+----+----------+--------+
| 1 | E1P1 | Empty |
| 2 | E1P2 | JOHN |
| 3 | E3P3 | Empty |
| 4 | E4P4 | MARK |
+----+----------+--------+
答案 0 :(得分:0)
我会在这里使用左连接:
SELECT
po.position_id,
po.position_name,
COALESCE(pe.people_name, 'EMPTY') AS STATUS
FROM position po
LEFT JOIN people pe
ON po.position_id = pe.people_position_id;
顺便说一句,您当前的右联接尝试失败的原因是您已将people
表放置在联接的右侧。这意味着不匹配的位置记录将被丢弃。这是我上面的答案,是使用右连接重写的:
SELECT
po.position_id,
po.position_name,
COALESCE(pe.people_name, 'EMPTY') AS STATUS
FROM people pe
RIGHT JOIN position po
ON po.position_id = pe.people_position_id;
请注意,表顺序已切换。在大多数情况下,您会看到人们使用左联接而不是右联接。