【发布时间】:2014-12-23 07:01:44
【问题描述】:
我有以下表格:
CREATE TABLE Company (
CompanyUniqueID BIGSERIAL PRIMARY KEY NOT NULL,
Name VARCHAR (150) NOT NULL
);
CREATE TABLE Item (
ItemUniqueID BIGSERIAL PRIMARY KEY NOT NULL,
CompanyUniqueID BIGINT NULL REFERENCES company DEFERRABLE INITIALLY DEFERRED,
Name VARCHAR (150) NOT NULL,
AddedDate TIMESTAMP without time zone DEFAULT now()
);
在应用程序的生命周期中,新的公司和项目被添加到表中。 我希望创建一个 sql 查询,从给定日期选择“新添加的公司” 我从这个查询开始:
(Select * from company
where companyuniqueid in (
select distinct companyuniqueid from Item where AddedDate > '2014-10-25'))
上述情况不好,因为在 2014-10-25 之后添加并且属于已经存在的公司的项目也会被选中。
例如,2014 年 10 月 20 日Company 表的快照可能如下所示:
1 AAA
2 BBB
3 CCC
表格项看起来像:
1 1 111 2014-10-01
2 2 222 2014-10-10
3 2 333 2014-10-10
4 3 444 2014-10-15
2014-10-26 增加了以下记录:
表公司
4 DDD
表格项目
5 1 555 2014-10-26
6 3 663 2014-10-26
7 4 777 2014-10-27
我已尝试将此添加到查询中:
(Select * from company
where companyuniqueid in (
select distinct companyuniqueid from Item
where AddedDate > '2014-10-25')
and companyuniqueid not in (
select distinct companyuniqueid from Item
where AddedDate <= '2014-10-25'))
但是我得到一个空的结果,为了只收到 4 个 DDD 应该是什么查询?
【问题讨论】:
-
AddedDatesupposed 是否允许 NULL 值?作为NOT NULL约束的候选者,让我印象深刻。
标签: sql postgresql exists