我有2个名为table_one
和table_two
的表,其中包含以下属性:
column_id
的公共列。table_one.column_id
的值是唯一的,而table_two.column_id
的值则不是。table_two
有两个名为ts_one
和ts_two
的额外列。 ts_one
不为空,但ts_two
可能为null。每table_two.column_id
只允许一行允许ts_two
值为空。table_one.column_id
中的所有值都可以在table_two.column_id
中显示。例如:
table_one
column_id
1
2
3
4
5
table_two
column_id ts_one ts_two
2 2014-10-01 null
3 2014-10-02 2014-10-03
3 2014-10-05 null
4 2014-10-01 2014-10-05
我需要从table_one.column_id
获取所有ID,其中:
table_one.column_id
而不是table_two.column_id(1,5满足)table_one.column_id
和table_two.column_id
中的{,其中ts_two
不为空且没有其他具有相同ID的行,其中ts_two
具有空值 - (仅满足4) 应考虑这两个条件。结果应包括1,4和5。
答案 0 :(得分:0)
第一个问题" table_one.column_id中的id而不是table_two.column_id中的id(1,5) "
此查询应该
SELECT column_id
FROM table_one AS o
WHERE NOT EXISTS (SELECT 1 FROM table_two WHERE column_id = o.column_id)
对于你的第二个问题" id在table_one.column_id和table_two.column_id中,其中ts_two不为null且没有id为空值 - (仅4)"
此查询也应该
SELECT t.* FROM table_two AS t
INNER JOIN table_one AS o ON o.column_id = t.column_id
WHERE t.ts_two IS NOT NULL AND NOT EXISTS (SELECT 1 FROM table_two WHERE ts_two IS NULL AND column_id = o.column_id)
这个问题太令人困惑了。但是根据下面的评论,这应该可以满足您的需求
SELECT DISTINCT column_id
FROM (
SELECT column_id
FROM table_one AS o
WHERE NOT EXISTS (SELECT 1 FROM table_two WHERE column_id = o.column_id)
UNION
SELECT t.column_id FROM table_two AS t
INNER JOIN table_one AS o ON o.column_id = t.column_id
WHERE t.ts_two IS NOT NULL AND NOT EXISTS (SELECT 1 FROM table_two WHERE ts_two IS NULL AND column_id = o.column_id)
) AS t
答案 1 :(得分:0)
更新小提琴:http://sqlfiddle.com/#!2/0b39d2/15/0
SELECT *
FROM Table_one A
LEFT JOIN Table_Two B
on A.Column_ID = B.ColumN_ID
LEFT JOIN (Select column_ID
From table_two
where ts_one is null or ts_two is null) C
ON A.ColumN_Id = C.Column_ID
WHERE C.Column_ID is null
OR B.Column_ID is Null;
这是做什么的:
答案 2 :(得分:0)
您可以使用单个联接和聚合来执行此操作...
SELECT t1.column_id FROM table_one AS t1
LEFT JOIN (
SELECT column_id, (COUNT(column_id) = COUNT(ts_two)) as no_nulls FROM table_two
GROUP BY column_id
) AS t2
ON t1.column_id = t2.column_id
WHERE t2.column_id IS NULL OR (t2.column_id IS NOT NULL AND t2.no_nulls = TRUE)
SQLFiddle:http://sqlfiddle.com/#!2/14855/8/0