表A(id,tid,...)
    1  001
    2  002
    3  
    4  003表B(tid,name,...)
    000 ABC
    001 BCD
    002 CDE现在的问题是:查询表A中tid在表B中存在的记录。
这个很简单,我用select A.id,A.tid from A where A.tid in (select tid from B) 不过,这里有一个特例,请看表A中第3条记录,tid是空的。所以上述语句得到的结果只有两条记录。
我想要:如果表A中tid为空,那么它就对应于表B中tid为000的记录。这样结果就是三条记录。请高手赐教!谢了!

解决方案 »

  1.   

    if object_id('[ta]') is not null drop table [ta]
    go
    create table [ta] (id int,tid nvarchar(6))
    insert into [ta]
    select 1,'001' union all
    select 2,'002' union all
    select 3,null union all
    select 4,'003'
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb] (tid nvarchar(6),name nvarchar(6))
    insert into [tb]
    select '000','ABC' union all
    select '001','BCD' union all
    select '002','CDE'
    select a.id,
           a.tid
    from ta a ,tb b
    where b.tid=(case when a.tid is null then '000' else a.tid end)
    /*
    id          tid
    ----------- ------
    1           001
    2           002
    3           NULL(3 個資料列受到影響)*/
      

  2.   

    if object_id('[ta]') is not null drop table [ta]
    go
    create table [ta] (id int,tid nvarchar(6))
    insert into [ta]
    select 1,'001' union all
    select 2,'002' union all
    select 3,null union all
    select 4,'003'
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb] (tid nvarchar(6),name nvarchar(6))
    insert into [tb]
    select '000','ABC' union all
    select '001','BCD' union all
    select '002','CDE'
    select a.id,
           a.tid
    from ta a ,tb b
    where b.tid=isnull(a.tid,'000')
    /*
    id          tid
    ----------- ------
    1           001
    2           002
    3           NULL(3 個資料列受到影響)
    */
      

  3.   

    select *
    from 表A
    where isnull(tid,'000') in (select tid from 表B)
      

  4.   

    select *
    from 表A
    where tid in (select tid from 表B) and tid is null
      

  5.   

    select *
    from A
    where A.tid isnull(tid,'000') and A.tid=B.tid;