日期:2014-05-18  浏览次数:20820 次

一题目,求多方法
SQL code
create table T( id int,name varchar(4))
insert into T values(1,'A'),(1,'B'),(2,'A'),(2,'C'),(3,'C');
--选出name有A无B的id号
--方法一:
select * from (select * from T where name='A')as a where ID<>(select id from T where name='B')

还有别的方法来实现吗?

------解决方案--------------------
SELECT * FTOM T T1 
WHERE NOT EXISTS(SELECT 1 FROM T WHERE ID=T1.ID AND NAME<>T1.NAME AND NAME='B')
and t1.name='a'
------解决方案--------------------
select t1.* from T as t1
inner join T t2 on (t1.id = t2.id and t1.name <> t2.name) 
and t2.name <> 'B'
where t1.name = 'A'
------解决方案--------------------
SQL code

create table T( id int,name varchar(4))
insert into T values(1,'A'),(1,'B'),(2,'A'),(2,'C'),(3,'C');


select t1.*
from T t1
where t1.name='A' and not exists
(select 1 from T t2 
where t2.id=t1.id and t2.name='B')

/*
id          name
----------- ----
2           A

(1 row(s) affected)
*/

------解决方案--------------------
SQL code
SELECT  *
FROM    t AS a
WHERE   NAME = 'a'
        AND NOT EXISTS ( SELECT 1
                         FROM   t
                         WHERE  id = a.id
                                AND NAME = 'b' )