现在有两张表,内容分别为,其中cid为tabledetails表的主键,在tablemain中可为空tablemain
id  cid
1    1
2    1
3    2
4   null
5   nulltabledetails
cid  name
1    中国
2    美国
3    日本现在求一句select语句,使得输出结果为:id  cid  name
1    1   中国
2    1   美国
3    2   日本
4   null null
5   null null求该SQL语句!

解决方案 »

  1.   

    select a.*,
           b.name
    from tablemain a left join tabledetails b
    on a.cid=b.cid
      

  2.   

    select t.*,r.name
    from tablemain t left join 
    tabledetails r on t.id=r.cid
      

  3.   

    select a.*,b.name
    from tablemain a
    left join tabledetails b
    on a.id=b.cid
      

  4.   

    select A.id ,A.cid, B.name from tablemain A, tabledetails B where A.id=B.cid
      

  5.   

    select t.*,r.name
    from tablemain t left join 
    tabledetails r on t.id=r.cid
      

  6.   


    ---测试数据---
    if object_id('[tablemain]') is not null drop table [tablemain]
    go
    create table [tablemain]([id] int,[cid] int)
    insert [tablemain]
    select 1,1 union all
    select 2,1 union all
    select 3,2 union all
    select 4,null union all
    select 5,null
    if object_id('[tabledetails]') is not null drop table [tabledetails]
    go
    create table [tabledetails]([cid] int,[name] varchar(4))
    insert [tabledetails]
    select 1,'中国' union all
    select 2,'美国' union all
    select 3,'日本'
     
    ---查询---
    select a.*,b.name
    from tablemain a
    left join tabledetails b
    on a.id=b.cid
    ---结果---
    id          cid         name 
    ----------- ----------- ---- 
    1           1           中国
    2           1           美国
    3           2           日本
    4           NULL        NULL
    5           NULL        NULL(所影响的行数为 5 行)
      

  7.   

    select a.*,b.name
    from tablemain a
    left join tabledetails b
    on a.id=b.cid数据有问题吧
      

  8.   


    select a.*,b.name from tablemain a left join tabledetails b on a.cid=b.id
      

  9.   

    select t.*,r.name
    from tablemain t left join 
    tabledetails r on t.id=r.cid
      

  10.   

    select a.*,b.name from tablemain a left join tabledetails b on a.cid=b.id
      

  11.   

    因为是以左边为基准查右边表匹配的值,并查找出左边有,而右边表不匹配的数据
    所以要用左连接查询:
    select a.*,
           b.name
    from tablemain a left join tabledetails b
    on a.cid=b.cid
      

  12.   

    select a.*,b.name
    from tablemain a left join tabledetails b on a.cid=b.cid
      

  13.   

    select a.*,b.name
    from tablemain a left join tabledetails b on a.cid=b.cid
      

  14.   


    SELECT A.*,B.name FROM tablemain A left join tabledetails B
    A.cid = B.cid
      

  15.   

    select A.id,A.Cid,B.[name]
    from details B right join 
    main A on A.id=B.cid
    result
    //-*-------
    1 1 中国
    2 1 美国
    3 2 日本
    4 NULL NULL
    5 NULL NULL
      

  16.   


    select a.id,a.cid,b.name from  tablemain a left join tabledetails b on a.id=b.cid
      

  17.   

    select a.*,
           b.name
    from tablemain a left join tabledetails b
    on a.cid=b.cid