过滤数据库中的记录

Filter records in database

enter image description here我有一个 table 包含 3 列 ID、单元和过程:

|Id  |Unit  |Process   |
|----|------|----------|
|100 |1     |0         |
|100 |0     |5         |
|101 |1     |0         |

输出

|Id  |Unit  |Process   |
|----|------|----------|
|101 |1     |0         |

我想排除所有进程值为 5 的 ID。

所以 ID 100 有一个进程 5,所以 ID 100 的所有行都将被删除 我还想要附加条件,所有记录在输出集中的单位值都应为 1。

这是我尝试过的,但我需要简短的查询

Select id,unit, process from table a where id in
(
Select distinct id from table a where unit=1
)
And id not in
(
Select distinct id from table a where process=5
)

您正在寻找 WHERE NOT EXISTS

数据设置:

CREATE TABLE mytable(
   Id      INTEGER  NOT NULL
  ,Unit    INTEGER  NOT NULL
  ,Process INTEGER  NOT NULL
);
INSERT INTO mytable(Id,Unit,Process) VALUES (100,1,0);
INSERT INTO mytable(Id,Unit,Process) VALUES (100,0,5);
INSERT INTO mytable(Id,Unit,Process) VALUES (101,1,0);

查询:

SELECT 
  *
FROM mytable AS m1
WHERE 
  m1.Unit = 1
  AND
  NOT EXISTS (SELECT 1 
              FROM mytable AS m2 
              WHERE m1.ID = m2.ID AND m2.Process = 5);

结果:

+-----+------+---------+
| Id  | Unit | Process |
+-----+------+---------+
| 101 |   1  |       0 |
+-----+------+---------+

您可以使用 EXISTS 而不是 EXISTS,这样,您将能够return所有成功 ID 的记录:

;with tableA as
(select 100 as id,1 as unit,5 as Process union
select 100,0,5 union
select 101,1,0)

Select * from tableA a
where EXISTS
      (Select 1 from tableA b where a.id=b.id and b.unit=1) 
      AND NOT EXISTS
      (Select 1 from tableA c where a.id=c.id and c.process=5)