时间序列表的sql并集,忽略/删除重复项

nwnhqdif  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(371)

我在找一些关于postgresql查询的帮助。我有两个表中的子查询,两个表都有相同的所有列,但两个表中的数据可能不同:
tab1(有时可能为空,因为子查询中不满足条件语句)

  1. +---------+------------+
  2. | ts | value |
  3. +---------+------------+
  4. | 1 | 1002 |
  5. | 2 | 3234 |
  6. | 3 | 530 |
  7. | 4 | 340 |
  8. +---------+------------+

tab2(总是有数据)

  1. +---------+------------+
  2. | ts | value |
  3. +---------+------------+
  4. | 1 | 1303 |
  5. | 2 | 9000 |
  6. | 3 | 4003 |
  7. | 4 | 924 |
  8. | 5 | 225 |
  9. | 6 | 346 |
  10. +---------+------------+

我需要用tab2值扩展tab1。因此,如果两个表中的ts(时间步长)相同,我将它们连接起来并丢弃重复的行。我想到了这个:
使用my\u select as(select ts,value,from tab1)select*from my\u select union all select ts,value from tab2 where and ts>(选择max(ts)from my\u select)

  1. +---------+------------+
  2. | ts | value |
  3. +---------+------------+
  4. | 1 | 1002 |
  5. | 2 | 3234 |
  6. | 3 | 530 |
  7. | 4 | 340 |
  8. | 5 | 225 |
  9. | 6 | 346 |
  10. +---------+------------+

显然,这种连接只有在第一个表有数据时才起作用,否则max(ts)失败并且没有数据出现。理想情况下,在这种情况下,如果没有tab1数据可用,我只希望返回tab2数据。请问有没有更优雅的解决方案?

mccptt67

mccptt671#

我想你可以用它做你想做的事 union all 以及 not exists :

  1. select ts, value
  2. from tab1
  3. union all
  4. select t1, value
  5. from tab2
  6. where not exists (select 1 from tab1 where tab1.ts = tab2.ts);

相关问题