【问题标题】:Mysql select row having only specified values in a columnMysql选择列中只有指定值的行
【发布时间】:2015-12-09 00:00:56
【问题描述】:

您好,我有一个名为 student_subject_table 的 mysql 表:

+----+-------------+---------------------+ 
| id | student_id  | subject             | 
+----+-------------+---------------------+ 
|  1 |           7 | math                | 
|  2 |           7 | physics             |  
|  3 |           7 | chemistry           |  
|  8 |           8 | math                | 
|  9 |           8 | physics             | 
| 10 |           8 | chemistry           | 
| 11 |           8 | biology             |  
+----+-------------+---------------------+ 

我正在尝试获取仅以数学、物理和化学为科目的学生的 ID。

我试过 in 子句:

 select student_id
 from student_subject table
 where
   subject in ('math', 'physics', 'chemistry')
 GROUP BY (student_id)

正如预期的那样,我得到了 7 和 8 作为 student_id。 在上表中,我只需要 student_id = 7。

mysql有什么办法可以做到吗?

请帮忙。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    你可以使用这个查询:

    select student_id
    from student_subject table
    group by student_id
    having
      SUM(subject IN ('math', 'physics', 'chemistry')) = COUNT(DISTINCT subject)
      AND COUNT(DISTINCT subject)=3
    
    • SUM(subject IN ('math', 'physics', 'chemistry')) 将是学生 7 和 8 的 3
    • COUNT(DISTINCT subject) 学生 7 为 3,学生 8 为 4

    如果(student_id, subject) 是唯一的,您可以将COUNT(DISTINCT ...) 替换为COUNT(*)

    只有学生 7 会被退回。

    【讨论】:

      【解决方案2】:

      使用 DISTINCT 子句

      SELECT DISTINCT student_id 
      FROM student_subject_table 
      WHERE subject IN ('math', 'physics', 'chemistry') 
      GROUP BY (student_id);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        • 2014-11-28
        • 1970-01-01
        • 2021-12-11
        相关资源
        最近更新 更多