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

标签 mysql sql select records

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

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/

相关文章:

php - SQL - 将多个文本记录合并为一个

sql - SQL 语句中的全局变量

select - swt 表更改选择项颜色

java - hibernate中查询两个有PK FK关系的表

mysql - 根据评论从论坛中选择话题

mysql - 无法更改 MySQL 5.7 中的字符集(从拉丁语到 utf8)

php - 链接存储在变量中,并且想在php中从中获取参数

sql - HAVING子句中的CASE语句

php - 使用 PHP OOP 连接到数据库

php - 删除MYSQL中的一堆转义引号