代码之家  ›  专栏  ›  技术社区  ›  ferret96

mysql-选择不包含特定值的所有唯一记录

  •  1
  • ferret96  · 技术社区  · 6 年前

    (如果之前有人问过这个问题或者这个问题太简单,那么很抱歉)

    从表中选择所有学生的唯一名称,其中level='high school'和没有体育('soccer'、'basketball')科目。

    ID      name    level          subject
    
    00001   John    High school Science
    00002   John    High school Math
    00003   John    High school *Soccer*
    00004   John    High school English
    00005   Andrea  High school Math
    00006   Andrea  High school Science
    00007   Andrea  High school English
    00008   Susan   High school History
    00009   Susan   High school English
    00010   Susan   High school Math
    00011   Michael High school Since
    00012   Michael High school Math
    00013   Michael High school *Basketball*
    00014   Michael High school English
    00015   Mary    Middle school   Math
    

    我尝试使用“exists”如下:

    SELECT ID, name, level FROM Students WHERE level = 'High school' AN NOT EXISTS(
       SELECT * FROM Students WHERE subject IN ('Soccer', 'Basketball') );
    

    结果应该是:

    Andrea  High school
    Susan   High school
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   GMB    6 年前

    你需要 相关 使用外部查询的子查询 name 专栏:

    SELECT DISTINCT s.name,  s.level
    FROM students s
    WHERE s.level = 'High school'
    AND NOT EXISTS (
        SELECT 1 FROM students s1 WHERE s1.name = s.name AND s1.subject IN ('Soccer', 'Basketball')  
    )
    

    如果没有关联,子查询实际上会检查 全部的 记录在 students 主题不同于 'Soccer' 'Basketball' ,这是错误的,导致外部查询没有返回任何结果。

    这个 demo on Db Fiddle 通过您的示例数据,可以得出:

    | name   | level       |
    | ------ | ----------- |
    | Andrea | High school |
    | Susan  | High school |
    
        2
  •  0
  •   Jo Joseph    6 年前

    请试试这个。

    SELECT DISTINCT ID, name, level FROM Students WHERE level = 'High school' AND  subject NOT IN ('Soccer', 'Basketball') ;