mySQL查询如何根据另一列选择值

时间:2017-09-29 06:49:03

标签: mysql

我想选择讲授至少两个不同年级的讲师。 例如,讲授年级2和9的讲师222222。 我应该写什么查询语句才能实现? enter image description here

2 个答案:

答案 0 :(得分:3)

您可以使用聚合函数计数和年级别的不同过滤器来获取讲师,然后使用having子句过滤您的聚合结果

select lecturer
from table
group by lecturer
having count(distinct yearlevel) >= 2

答案 1 :(得分:0)

我想到了两个问题。第一个借用问题本身的语言,并在COUNT DISTINCT子句中使用HAVING

select lecturer                         -- "select the lecturer"
from myTable
group by lecturer
having count(distinct yearlevel) >= 2   -- "who teaches at least two distinct yearlevel"

第二种是使用EXISTS的特例。既然你正在寻找两个截然不同的年级,我们可以将其重写为“另外一年级教学”。根据您希望如何投影结果和/或优化程序决定执行的操作,这可能很有用:

select *
from myTable a
where exists (
    select 1 
    from myTable b 
    where b.lecturer = a.lecturer 
    and b.yearlevel <> a.yearlevel)