SQL - 如何选择具有特定条件的行?
Posted
技术标签:
【中文标题】SQL - 如何选择具有特定条件的行?【英文标题】:SQL - How to select the row that has specific condition? 【发布时间】:2018-12-24 15:53:20 【问题描述】:我是 SQL 领域的新手,我在 Windows 7 中使用 MariaDB 10.1。
这是我创建的测试代码。
CREATE TABLE sample (
studentName VARCHAR(32),
subjectName VARCHAR(16),
subjectRegistration BOOLEAN
);
INSERT
INTO sample VALUES
("Tom", "Math", TRUE),
("Tom", "English", TRUE),
("Tom", "Science", TRUE),
("Jane", "English", TRUE),
("Jane", "Math", TRUE),
("Jane", "Science", TRUE),
("Peter", "Math", TRUE),
("Susan", "Math", TRUE),
("Susan", "Science", TRUE),
("Clark", "Math", TRUE),
("Clark", "English", TRUE),
("Clark", "Science", TRUE);
我想选择只选修数学的学生。(在本例中是 Peter。)
SELECT * FROM sample WHERE subjectName = 'Math' AND subjectRegistration = TRUE;
此查询不仅选择 Peter,还选择注册其他科目的所有人。
我应该使用什么查询?
感谢您的提前。
【问题讨论】:
【参考方案1】:您想要做的是包含仅数学的学生。如何在 sql 中执行此操作有多种变体。总体思路是找出谁上过数学并且只上过一门课。这些只是其中的几个示例,但每个示例都能完成您的任务。
您可以在Sql Fiddle 上查看每个示例。
示例 1:
SELECT *
FROM sample
WHERE subjectName = 'Math'
AND subjectRegistration = TRUE
AND studentName IN (SELECT studentName
FROM sample
WHERE subjectRegistration = TRUE
GROUP BY studentName
HAVING count(*) = 1)
示例 2:
SELECT *
FROM sample s
JOIN (SELECT studentName
FROM sample
WHERE subjectRegistration = TRUE
GROUP BY studentName
HAVING count(*) = 1) s2 ON (s.studentName = s2.studentName)
WHERE s.subjectName = 'Math'
AND subjectRegistration = TRUE
【讨论】:
啊自我加入是关键!第一个看起来更好理解,但我喜欢 join 方法。谢谢! XD【参考方案2】:我会使用not exists
:
select s.*
from sample s
where subjectRegistration = true and
not exists (select 1
from sample s1
where s1.studentName = s.studentName and
s1.subjectName <> 'Math'
);
【讨论】:
以上是关于SQL - 如何选择具有特定条件的行?的主要内容,如果未能解决你的问题,请参考以下文章