一道练习题就是查询跟蒋雯丽选了同样书的人的姓名,书名还有借书日期    
不知道我的代码哪里错了  就是蒋雯丽没有选海贼王  也会查出来
想不通 大家帮我分析下

解决方案 »

  1.   

    楼主这个exists没起作用吧,exists里边和外边有关联吗?
    另外楼主的语句没有搜索出来蒋雯丽相关数据啊
      

  2.   

    --测试数据
    if not object_id(N'Tempdb..#T') is null
    drop table #T
    Go
    Create table #T([姓名] nvarchar(23),[书名] nvarchar(24))
    Insert #T
    select N'张三',N'三国演义' union all
    select N'蒋雯丽',N'三国演义' union all
    select N'李四',N'海贼王'
    Go
    --测试数据结束
    SELECT *
      FROM #T a
     WHERE EXISTS (SELECT * FROM #T b WHERE a.书名 = b.书名 AND b.姓名 = '蒋雯丽')
       AND a.姓名 <> '蒋雯丽'
      

  3.   

    with borrower as (
    select '120101' as 借书证号,'蒋雯丽' as 姓名,'计算机系' as 系名,'12-1' as 班级
    union all
    select '120102','刘昌伟','计算机系','12-1'
    union all
    select '120103','宋美娜','计算机系','12-1'
    union all
    select '220101','杰弗森','英语系','22-1'
    union all
    select '220102','内丹','英语系','22-1'
    union all
    select '220103','刘东升','英语系','22-1'
    union all
    select '120104','赵日天','计算机系','12-2'
    ),loans as (
    select '120101' as 借书证号,'y100' as 图书馆登记号,getdate() as 借书日期
    union all
    select '120101','y102',getdate()
    union all
    select '120101','y103',getdate()
    union all
    select '120101','y104',getdate()
    union all
    select '120101','y105',getdate()
    union all
    select '120103','y104',getdate()
    union all
    select '120104','y103',getdate()
    union all
    select '220102','y101',getdate()
    union all
    select '220101','y104',getdate()
    ),books as (
    select 'tp311' as 索书号,'数据库系统' as 书名,'黎明' as 作者,'y100' as 图书馆登记号
    union all
    select 'tp312','海贼王','黎明','y101'
    union all
    select 'tp313','西游记','黎明','y102'
    union all
    select 'tp314','三国演义','黎明','y103'
    union all
    select 'tp315','三体','黎明','y104'
    union all
    select 'tp316','镜花缘','黎明','y105'
    )
    select 姓名,书名 
    from loans l
    inner join borrower u on l.借书证号=u.借书证号
    inner join books b on b.图书馆登记号=l.图书馆登记号
    where l.图书馆登记号 in (
    select 图书馆登记号 
    from loans 
    where 借书证号=(
    select 借书证号 
    from borrower 
    where 姓名='蒋雯丽'
    )
    )
    and 姓名<>'蒋雯丽'直接就没用exists
      

  4.   

    select 姓名,书名 
    from loans l
    inner join borrower u on l.借书证号=u.借书证号
    inner join books b on b.图书馆登记号=l.图书馆登记号
    where exists(
    select top 1 1 from loans x
    inner join borrower y on x.借书证号=y.借书证号
    where 姓名='蒋雯丽' and x.图书馆登记号=l.图书馆登记号
    )
    and 姓名<>'蒋雯丽'修改成exists了