场景:我有一个状态为活动或已删除的表。假设我们正在谈论车主。表中的状态可以反映以下事实:以前有2个所有者(即-已删除状态),并且表中只有1个当前所有者处于“活动”状态。
问题:我将如何编写一个涉及此类表的查询,以仅包含没有当前所有者的结果(即-该车没有处于“活动”状态的行)?< / p>
仅当至少有一行符合上述条件时,以下内容才匹配。因此,对于我要查找的内容无效:
SELECT *
FROM car_owners
WHERE status = 'deleted'
SELECT *
FROM car_owners
WHERE status != 'active'
答案 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 |
+--------+----------+-----------+