SQL-如何选择具有特定条件的行?

时间:2018-07-17 03:55:15

标签: mysql sql select mariadb

我是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);

我想选择只注册数学的学生。(在这种情况下,是彼得。)

SELECT * FROM sample WHERE subjectName = 'Math' AND subjectRegistration = TRUE;

此查询不仅选择Peter,还选择所有注册其他主题的人。

我应该使用什么查询?

感谢您的进阶。

2 个答案:

答案 0 :(得分:2)

您想做的是包括数学的学生。关于如何在sql中执行此操作,存在多种变体。总体思路是找出谁修过数学并且只修了1门课程。这些只是一些示例,但每个示例都能完成您的任务。

您可以在此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 

答案 1 :(得分: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'
                 );