我创建了以下简单表格来说明我们要解决的问题:
CREATE TABLE soPost
(
id INT AUTO_INCREMENT,
code INT,
value VARCHAR(8),
PRIMARY KEY(id)
);
该表已填充以下插入语句:
INSERT INTO soPost(code, value)
VALUES (101, 'XYZ'), (101, 'ABC'), (101, 'DEF'), (101, 'GHI'),
(201, 'XYZ'), (201, 'ABC'), (201, 'JKL'),
(301, 'XYZ'), (301, 'DEF'), (301, 'MNO'),
(401, 'XYZ'), (401, 'PRQ'),
(501, 'STU'), (501, 'VWZ');
结果
SELECT * FROM soPost;
是:
+----+------+-------+
| id | code | value |
+----+------+-------+
| 1 | 101 | XYZ |
| 2 | 101 | ABC |
| 3 | 101 | DEF |
| 4 | 101 | GHI |
| 5 | 201 | XYZ |
| 6 | 201 | ABC |
| 7 | 201 | JKL |
| 8 | 301 | XYZ |
| 9 | 301 | DEF |
| 10 | 301 | MNO |
| 11 | 401 | XYZ |
| 12 | 401 | PRQ |
| 13 | 501 | STU |
| 14 | 501 | VWZ |
+----+------+-------+
我们需要选择其中至少一个值是“ XYZ”但都不是“ ABC”或“ DEF”的代码。显然,满足此条件的唯一值是代码401。
请提出SQL查询以实现此结果。
答案 0 :(得分:1)
您可以使用NOT EXISTS
子查询来执行此测试:
SELECT code
FROM soPost s1
WHERE s1.value = 'XYZ' AND
NOT EXISTS (SELECT *
FROM soPost s2
WHERE s2.code = s1.code AND s2.value IN('ABC', 'DEF'))
输出:
code
401
答案 1 :(得分:0)
您可以使用子数据集:
select distinct(code) from soPost
where
code not in (
select distinct(code) from soPost where value = "ABC" or value = "DEF"
)
and
code in (
select code from soPost where value='XYZ'
);