无活动状态的SQL查询

时间:2019-08-12 14:38:43

标签: mysql sql database status

场景:我有一个状态为活动或已删除的表。假设我们正在谈论车主。表中的状态可以反映以下事实:以前有2个所有者(即-已删除状态),并且表中只有1个当前所有者处于“活动”状态。

问题:我将如何编写一个涉及此类表的查询,以仅包含没有当前所有者的结果(即-该车没有处于“活动”状态的行)?< / p>

仅当至少有一行符合上述条件时,以下内容才匹配。因此,对于我要查找的内容无效:

测试查询1

SELECT *
FROM car_owners
WHERE status = 'deleted'

测试查询2

SELECT *
FROM car_owners
WHERE status != 'active'

2 个答案:

答案 0 :(得分:3)

我想你想要

select co.*
from car_owners co
where not exists (select 1
                  from car_owners co2
                  where co2.car_id = co.car_id and co2.status = 'active'
                 );

如果只需要car_id,则可以使用聚合:

select co.car_id
from car_owners co
group by co.car_id
having not max( status = 'active' );

您还可以将having的短语设置为:

having min(status) = 'deleted'

答案 1 :(得分:0)

您可以为此使用NOT IN运算符。


表结构和样本数据

CREATE table car (
  carid int, 
  ownerid int, 
  carstatus varchar(50)
);
INSERT INTO car 
VALUES 
  (1, 1, "active"), 
  (2, 3, "active"), 
  (3, 5, "active"), 
  (4, 11, "deleted"), 
  (4, 12, "deleted"), 
  (4, 23, "active"), 
  (5, 13, "deleted"), 
  (6, 35, "deleted"), 
  (6, 38, "deleted"), 
  (6, 53, "deleted"), 
  (6, 10, "active"), 
  (7, 13, "deleted"), 
  (8, 16, "deleted"); 

SQL查询

SELECT *
FROM   car
WHERE  carid NOT IN (SELECT carid
                     FROM   car
                     WHERE  carstatus = "active") 

输出

+--------+----------+-----------+
| carid  | ownerid  | carstatus |
+--------+----------+-----------+
|     5  |      13  | deleted   |
|     7  |      13  | deleted   |
|     8  |      16  | deleted   |
+--------+----------+-----------+

在线演示:http://sqlfiddle.com/#!9/0746c1/9/0