【发布时间】:2019-01-08 18:33:11
【问题描述】:
我正在尝试在 2018 年 6 月之前和 12 月 1 日之后获取产品。我想一个简单的方法是通过两个子查询,然后在外部查询中彼此相邻地调用它们。运行此程序时,我得到了其中一个子查询的正确数据,而另一个只是为另一个查询的每个不同结果重复相同的 id 和 created_at。
with x as (select id, created_at
from products p
where created_at < '2018-06-01'
and approved = 't'),
y as (select id, created_at
from products p
where created_at > '2018-12-01'
and approved = 't')
select * from x,y
limit 100;
Results look like :
id | created_at | id2 | created_at2
1 2012-12-05 5 2018-12-20
2 2012-12-06 5 2018-12-20
3 1993-05-23 5 2018-12-20
4 2005-03-10 5 2018-12-20
...
Expected results:
id | created_at | id2 | created_at2
1 2012-12-05 5 2018-12-22
2 2012-12-06 6 2018-12-31
3 1993-05-23 7 2018-12-27
4 2005-03-10 8 2018-12-06
【问题讨论】:
-
结果有什么关系?他们似乎不是。如果您只想并排显示它们,请在表示层中执行此操作并使用单独的查询。您在这里进行交叉连接,因此 x 中的每一行都将与 y 中的每一行连接,您会得到很多结果。
-
这很好。我不确定是否可以轻松地让他们连续展示他们的数据。
标签: postgresql time subquery common-table-expression