【问题标题】:Help with query帮助查询
【发布时间】:2010-04-27 17:11:02
【问题描述】:

我正在尝试进行查询以查看单个表,以查看学生是否在名为 CMHT 的团队和医疗团队中 - 如果他们是,我不想看到结果。

我只想查看他们仅在 CMHT 或 medic 中的记录,而不是两者。

正确的方向是使用子查询来过滤掉它吗?我已经对 NOT IN 进行了搜索,但你怎么能看到它是否在超过 2 个团队中?

Student     Team          ref
1           CMHT           1
1           Medic          2
2           Medic          3 this would be in the result
3           CMHT           5 this would be in the result

到目前为止,我已经完成了以下代码,我需要使用子查询还是进行自联接并以这种方式过滤?

SELECT Table1.Student, Table1.Team, Table1.refnumber
  FROM Table1
 WHERE (((Table1.Team) In ('Medics','CMHT')) 

【问题讨论】:

  • 还有其他团队吗?如果学生既不在Medic 也不在CMHT,你想退回他们吗?

标签: sql mysql tsql


【解决方案1】:

这是 Mark Byers 用 HAVING 子句代替子查询的答案:

SELECT Student, Team, ref
FROM Table1
GROUP BY Student
HAVING COUNT(Student) = 1

【讨论】:

  • 嘿,谢谢 :) 想算一下.. :)
  • o ps 感谢大家的帮助 :) - 关于另一个主题,外部连接如何工作??
  • @hdoe123:另一个主题 = 另一个问题。
  • @Marcus Adams:+1 对我的回答进行了很好的改进! :)
【解决方案2】:
SELECT  *
FROM    students
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    students si
        WHERE   si.student = s.student
                AND si.team = 'CMHT'
        )
        OR NOT EXISTS
        (
        SELECT  NULL
        FROM    students si
        WHERE   si.student = s.student
                AND si.team = 'Medic'
        )

【讨论】:

    【解决方案3】:
    SELECT a.*
    FROM Table1 a
    INNER JOIN 
    ( SELECT Student, COUNT(*) FROM Table1 
    GROUP BY Student 
    HAVING COUNT(*) = 1)b
    ON (a.Student = b.Student)
    

    【讨论】:

      【解决方案4】:

      您如何查看它是否在 2 个或更多团队中?

      您可以计算每个学生的团队数量,然后只过滤您想查看的团队:

      SELECT student FROM
      (
          SELECT student, COUNT(*) AS cnt
          FROM Table1
          GROUP BY student
      ) T1
      WHERE cnt = 1
      

      【讨论】:

        【解决方案5】:

        你可以通过外部连接来做到这一点

        select COALESCE(t1.Student, t2.Student) as Student,
               COALESCE(t1.Team, t2.Team) as Team,
               COALESCE(t1.ref, t2.ref) as ref
        from
            (select * from Student where Team = 'CMHT') t1
            outer join
            (select * from Student where Team = 'Medic') t2
            on t1.Student = t2.Student
        where
            t1.Student is null or
            t2.Student is null;
        

        【讨论】:

        • MySQL 不支持FULL OUTER JOIN
        • 抱歉,不知道。看到问题也被标记为 tsql,并认为外连接的 SqlServer 语法和行为是有效的。