MySQL查询合并重复键(2个表)
我请求你理解,因为我英语说得不好 有两张桌子。MySQL查询合并重复键(2个表),mysql,Mysql,我请求你理解,因为我英语说得不好 有两张桌子。 主键是时间 A A time | A_temperature 1027 | 30 1028 | 30 1030 | 60 B B time | B_temperature 1027 | 40 1029 | 50 1030 | 20 1031 | 59 我想要以下结果 time | A_temperature | B_temperature 1027 | 30 | 40 1028 | 30
主键是时间
A
A time | A_temperature
1027 | 30
1028 | 30
1030 | 60
B
B time | B_temperature
1027 | 40
1029 | 50
1030 | 20
1031 | 59
我想要以下结果
time | A_temperature | B_temperature
1027 | 30 | 40
1028 | 30 | NULL
1029 | NULL | 50
1030 | 60 | 20
1031 | NULL | 59
因此,我提出了以下问题:
SELECT A.time, B.time, A_temperature, B_temperature
FROM A
JOIN B
ON (B.time >= '1027' AND B.time <= '1031')
WHERE (A.time >= '1027' AND A.time <= '1031')
GROUP BY A.time, B.time, A_temperature, B_temperature
选择A.时间、B.时间、A_温度、B_温度
从
加入B
在(B.time>='1027'和B.time='1027'和A.time上,您确实需要一个完整的外部联接。MySQL不直接支持完整的外部联接运算符,但我们可以很容易地使用左联接和右联接的并集来模拟
SELECT COALESCE(A.time, B.time) AS time, A_temperature, B_temperature
FROM A
LEFT JOIN B ON A.time = B.time
UNION ALL
SELECT COALESCE(B.time, A.time), A_temperature, B_temperature
FROM A
RIGHT JOIN B ON A.time = B.time
WHERE A.time IS NULL
ORDER BY time;
请注意,我们从两个表中的每个表中获取时间的合并
。这是可行的,因为可以保证两个表中的一个表始终存在非NULL
时间(否则它甚至不会成为连接查询的一部分)但是,并不总是保证两个表都有非NULL
时间