从MySQL表中选择数据

时间:2014-11-12 20:06:00

标签: mysql left-join

我有2个名为table_onetable_two的表,其中包含以下属性:

  • 他们都有一个名为column_id的公共列。
  • table_one.column_id的值是唯一的,而table_two.column_id的值则不是。
  • table_two有两个名为ts_onets_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,其中:

  1. id table_one.column_id而不是table_two.column_id(1,5满足)
  2. table_one.column_idtable_two.column_id中的{,其中ts_two不为空且没有其他具有相同ID的行,其中ts_two具有空值 - (仅满足4)
  3. 应考虑这两个条件。结果应包括1,4和5。

3 个答案:

答案 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;

这是做什么的:

  • 返回第1组
  • 中表1中的所有数据
  • 加入表2中不在1,5(将数据添加到第1组)
  • 的数据
  • 连接到表2中的数据,该数据已被过滤,仅包含带空值的记录(创建第2组)
  • 将第二次加入中存在匹配的记录排除在表二之外。 (过滤数据,以便仅返回第一组中的数据而不返回第二组中的数据。

答案 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

  1. 查询表1中的所有内容
  2. 查询表2中的每个id,以及该id是否有任何null ts_two条目。
  3. 如果2中缺少1,或者如果1在2并且没有null ts_two条目,则将它们连接在一起。