我如何能够加入下面的2个表格(A& B),以便我可以得到下面的结果表
请注意,查询应该加入具有相同时间的值,
(即结果表中显示如下2014-11-29 9:58:23 6054 1
)
表A
ID time noise
76676 2014-11-29 09:55:24 6636
76677 2014-11-29 09:55:32 5256
76678 2014-11-29 09:55:42 5066
76679 2014-11-29 09:56:09 11560
76680 2014-11-29 09:56:22 5656
76681 2014-11-29 09:56:50 7031
76682 2014-11-29 09:56:56 5069
76683 2014-11-29 09:57:06 10088
76684 2014-11-29 09:57:23 5589
76685 2014-11-29 09:58:23 6054
表B
ID time movement
789 2014-11-29 09:57:04 1
790 2014-11-29 09:57:10 1
791 2014-11-29 09:57:30 1
792 2014-11-29 09:57:34 1
793 2014-11-29 09:57:40 1
794 2014-11-29 09:57:43 1
795 2014-11-29 09:57:52 1
796 2014-11-29 09:58:09 1
797 2014-11-29 09:58:23 1
798 2014-11-29 09:58:31 1
结果:
time noise movement
2014-11-29 9:55:24 6636 null
2014-11-29 9:55:32 5256 null
2014-11-29 9:55:42 5066 null
2014-11-29 9:56:09 11560 null
2014-11-29 9:56:22 5656 null
2014-11-29 9:56:50 7031 null
2014-11-29 9:56:56 5069 null
2014-11-29 9:57:04 null 1
2014-11-29 9:57:06 10088 null
2014-11-29 9:57:10 null 1
2014-11-29 9:57:23 5589 null
2014-11-29 9:57:30 null 1
2014-11-29 9:57:34 null 1
2014-11-29 9:57:40 null 1
2014-11-29 9:57:43 null 1
2014-11-29 9:57:52 null 1
2014-11-29 9:58:09 null 1
2014-11-29 9:58:23 6054 1
2014-11-29 9:58:31 null 1
答案 0 :(得分:1)
您需要执行Jynus已经评论过的FULL OUTER JOIN
。
select t1.time,t1.noise,t2.movement
from TableA t1 left join TableB t2
on t1.time = t2.time
UNION
select t1.time,t1.noise,t2.movement
from TableA t1 right join TableB t2
on t1.time = t2.time;
根据您的上一条评论:这是正确的,因为该行来自RIGHT JOIN
,但您可以使用CASE
表达式稍微调整一下1} p>
case when t1.time is null then t2.time else t1.time end as time
或者只是在t2.time
查询中使用RIGHT JOIN
,如@Karlois指出
在此处查看演示http://sqlfiddle.com/#!2/d42d01/2
SELECT * FROM
(
select t1.time,t1.noise,t2.movement
from TableA t1 left join TableB t2
on t1.time = t2.time
UNION
select t2.time,
t1.noise,t2.movement
from TableA t1 right join TableB t2
on t1.time = t2.time
) tab
ORDER BY time;
答案 1 :(得分:1)
首先你需要将两个表的时间联合起来,然后用两个表创建连接以获得噪声和运动
SELECT ts.time, ta.noise, tb.movement
FROM (SELECT a.time from tablea a
UNION
SELECT b.time from tableb b) ts
LEFT OUTER JOIN tablea ta ON ts.time = ta.time
LEFT OUTER JOIN tableb tb ON ts.time = tb.time
答案 2 :(得分:0)
我喜欢union
和聚合完全外连接的方法:
select time, max(noise) as noise, max(movement) as movement
from ((select a.time, a.noise, NULL as movement
from tablea a
) union all
(select b.time, NULL, b.movement
from tableb b
)
) ab
group by time;