读书人

SQL 语句应该要用到EXISTS

发布时间: 2012-01-18 00:23:26 作者: rapoo

求一个SQL 语句,应该要用到EXISTS
表A
学号 分数
001 90
002 80
003 70
004 89

表B
学号 分数
001 90
002 90

想把A表中和B表分数不相同,A表中有,B表中没有的都查询出来,预想结果
学号 分数A 分数B
002 80 90
003 70 NULL
004 89 NULL
该如何写好?


[解决办法]

SQL code
declare @表A table (学号 varchar(3),分数 int)insert into @表Aselect '001',90 union allselect '002',80 union allselect '003',70 union allselect '004',89declare @表B table (学号 varchar(3),分数 int)insert into @表Bselect '001',90 union allselect '002',90select  a.学号 ,        a.分数 as 分数a ,        b.分数 as 分数bfrom    @表a a        left join @表b b on a.学号 = b.学号where   isnull(a.分数, 0) <> isnull(b.分数, 0)/*学号   分数a         分数b---- ----------- -----------002  80          90003  70          NULL004  89          NULL*/
[解决办法]
用full join

借用子兄弟

SQL code
declare @表A table (学号 varchar(3),分数 int)insert into @表Aselect '001',90 union allselect '002',80 union allselect '003',70 union allselect '004',89declare @表B table (学号 varchar(3),分数 int)insert into @表Bselect '001',90 union allselect '002',90SELECT ISNULL(a.学号,b.学号) AS 学号,a.分数,b.分数FROM @表A AS aFULL JOIN @表B AS b ON a.学号=b.学号 WHERE NULLIF(a.分数,b.分数) IS NOT NULL/*学号    分数    分数002    80    90003    70    NULL004    89    NULL*/
[解决办法]
SQL code
create table a([学号] varchar(10),[分数] int)insert aselect '001' ,90 union allselect '002', 80 union allselect '003' ,70 union allselect '004' ,89create table b([学号] varchar(10),[分数] int)insert bselect '001', 90 union allselect '002', 90goselect o.[学号],o.[分数],u.[分数] from(select a.[学号],a.[分数] from awhere not exists (select 1 from b where a.[学号]=b.[学号] and a.[分数]=b.[分数])) as oleft join b as u on o.[学号]=u.[学号]/*(所影响的行数为 3 行)学号  分数   分数---   ---   ----002    80    90003    70    NULL004    89    NULL*/godrop table a,b
[解决办法]
A表中 有,B表中没有的查出来 可以用 except 关键字

select * from A
except
select * from B
[解决办法]
SQL code
select * from a where not exists(select 1 from b where  a.[学号]=[学号] and a.[分数]=[分数])union allselect * from b where not exists(select 1 from a where  [学号]=b.[学号] and [分数]=b.[分数])
[解决办法]
探讨

我想问下这里的
SELECT ISNULL(a.学号,b.学号) AS 学号,a.分数,b.分数
FROM @表A AS a
FULL JOIN
@表B AS b ON a.学号=b.学号
WHERE NULLIF(a.分数,b.分数) IS NOT NULL
能如果改成AND,为什么结果会不对呀?


引用:
用full join
……

读书人网 >SQL Server

热点推荐