[2个不同的联接通过2个不同的列

问题描述 投票:0回答:1

在我的数据库上,我有2个表,用于注册何时以及哪些项目已添加到2个不同的列表中。他们看起来像这样:

  • list1:id,时间(时间戳),item_id(int4)
  • list2:id,时间(时间戳),item_id(int4)

每个列表中的项目可以出现多次(与添加到列表中的次数相同)。它们来自销售项目集(一个项目可以添加到两个列表中)。

使用SQL(postgresql),我想每天(日期,我不在乎确切的时间)和每个项目(同一item_id每天只出现一次,但可以在下一个再次出现)一起加入这两个列表天)。

我尝试了多种类型的联接,但没有任何效果!我该怎么办?

非常感谢!

sql postgresql
1个回答
0
投票

为什么要使用两个单独的表,而不是一个带有“类型”列的表?

无论如何,请使用union all

select time::date, item_id, count(*)
from ((select id, time, item_id, 1 as which
       from list1
      ) union all
      (select id, time, item_id, 2 as which
       from list2
      )
     ) l
group by time::date, item_id;
© www.soinside.com 2019 - 2024. All rights reserved.