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

我想要一个学过物理但没有学过化学的学生?

给我错误的结果?

任何输入?

4

3 回答 3

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')
于 2013-07-18T14:28:10.243 回答
3

这是集合内集合查询的示例。这是使用group byand的解决方案having

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')计算“物理”的行数。> 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;
于 2013-07-18T14:27:00.767 回答
1

你可以试试这个查询

SELECT  distinct m.id 
FROM from table_name m 
WHERE
    m.a1 like 'physics' 
    and m.a2 <>'chem';
于 2013-07-18T14:40:09.540 回答