gpt4 book ai didi

mysql - 如何创建处理丢失记录的 SQL 查询?

转载 作者:行者123 更新时间:2023-11-29 01:16:44 24 4
gpt4 key购买 nike

我有两个表,其中包含客户的年龄和高度。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com