如何获得和/或条件?

时间:2013-07-18 14:21:28

标签: mysql sql

select distinct a1.id
from m a1, m a2
on a1.Id = a2.Id
where a1.sub = 'physics' and a2.sub <> 'chem';

我想要一个“学过物理而不是化学的学生?”

给我错误的结果?

任何输入?

3 个答案:

答案 0 :(得分:4)

使用not exists

select * 
from m a1
where a1.sub = 'physics'  
and not exists (select 1 from m where id = a1.id and sub = 'chem')

答案 1 :(得分:3)

这是set-within-sets查询的示例。以下是使用group byhaving的解决方案:

select a.id
from m a
group by a.id
having sum(a.sub = 'physics') > 0 and
       sum(a.sub = 'chem') = 0;

表达式sum(a.sub = 'physics')计算“physics”的行数。 > 0表示必须至少有一个人在场。同样,第二个条款表示没有“chem”行。

这种方法的优点是您可以轻松地概括它。例如,要包括生物学的要求:

from m a
group by a.id
having sum(a.sub = 'physics') > 0 and
       sum(a.sub = 'bio') > 0 and
       sum(a.sub = 'chem') = 0;

答案 2 :(得分:1)

您可以尝试此查询

SELECT  distinct m.id 
FROM from table_name m 
WHERE
    m.a1 like 'physics' 
    and m.a2 <>'chem';