我有两张桌子,其中包含顾客的年龄和身高。
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;
然而(这里是扭曲)由于记录保持不稳定,两个表都有丢失的记录。 (例如,年龄为customerId 5,高度为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 |
+-----------+------------+------------+
答案 0 :(得分:4)
一种方法(他们是其他人,一如既往)
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
答案 1 :(得分:2)
MySql没有完整的外部联接,但您可以simulate one使用LEFT JOIN
,然后使用RIGHT JOIN
,并结合UNION
,这将结合使用+消除重复:
SELECT Ages.age, COALESCE(Heights.height, 0)
FROM Ages
LEFT OUTER JOIN Heights ON Ages.customerId=Heights.customerId
UNION
SELECT COALESCE(Ages.age, 0), Heights.height
FROM Ages
RIGHT OUTER JOIN Heights ON Ages.customerId=Heights.customerId;
答案 2 :(得分:1)
你真正需要的是full outer join
,但MySQL并不支持。相反,让所有客户都在子查询中并使用left outer join
:
select c.customerid, coalesce(a.age, 0) as age, coalesce(h.height, 0) as height
from (select customerid from ages union
select customerid from heights
) c left outer join
ages a
on a.customerid = c.customerid left outer join
heights h
on h.customerid = c.customerid;
答案 3 :(得分:0)
使用LEFT JOIN,IF条件为NULL
SELECT Ages.age, IF (Heights.height IS NULL, 0, Heights.height) AS height
FROM Ages
LEFT JOIN Heights ON Ages.customerId=Heights.customerId;
好的,快速回答......上面只会给你0作为身高。问题也变得很年轻,但为此,更好地获得所有客户ID,离开加入年龄和高度
最佳答案是接受的答案,我把它留在这里因为我学习了MySQL COALESCE()函数,XD