我有两个表,其中包含客户的年龄和高度。
Table: Ages
+-----------+------------+
|customerId | age |
+-----------+------------+
| 1 | 15 |
| 2 | 24 |
| 3 | 21 |
| 4 | 62 |
| 6 | 57 |
| 7 | 32 |
+-----------+------------+
Table: Heights
+-----------+------------+
|customerId | height |
+-----------+------------+
| 1 | 175 |
| 2 | 182 |
| 4 | 180 |
| 5 | 171 |
| 6 | 165 |
| 7 | 182 |
+-----------+------------+
我需要编写一个读取所有年龄和高度的 SELECT
查询。所以像这样...
SELECT Ages.age, Heights.height
FROM Ages INNER JOIN Heights ON Ages.customerId=Heights.customerId;
但是(这里是转折点)由于草率的记录保存,两个表中都缺少记录。 (例如,Ages 中的 customerId 5,Heights 中的 customerId 3)。
有没有一种方法可以编写查询,使其仍然有效,但在数据丢失时返回零?
即
+-----------+------------+------------+
|customerId | age | height |
+-----------+------------+------------+
| 1 | 15 | 175 |
| 2 | 24 | 182 |
| 3 | 21 | 0 |
| 4 | 62 | 180 |
| 5 | 0 | 171 |
| 6 | 57 | 165 |
| 7 | 32 | 182 |
+-----------+------------+------------+
最佳答案
一条路要走(他们是其他人,一如既往)
select customerId, max(age), max(height)
from
(
select customerId, age, 0 as height from Ages
UNION
select customerId, 0 as age, height from heights
) s
group by customerId;
参见 SqlFiddle
关于mysql - 如何创建处理丢失记录的 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176611/