数据库为sqlserver
表1:table1
字段:itemid title
表2:table2
字段id,itemid
表2中itemid是对应表1中itemid的,但是不是表1中的每个数据,在表2中均有对应,比如表1中有10条数据,而表2中只对应了表1中的2条数据,其余8条均没有我需要的功能如下
我需要查询表1中的数据,优先显示表2中有记录的2条数据,而表1中的其他8条数据则随后显示请问此sql语句怎么写,非常感谢!!!!!千万别告诉我这样写select table1.*,table2.*  from table2.* left join table1 on table1.itemid =table2.itemid order by table2.id,因为这样只能得到2条数据,我需要得到10条数据

解决方案 »

  1.   


    select table1.* from table1 a ,table2 b where a.itemid=b.itemid union all
    select table1.* from table1 a where a.itemid not in (select itemid from table2) 
      

  2.   


    create table a (itemid int,title varchar(50))
    insert a select 1,'a1'
    insert a select 2,'a2'
    insert a select 3,'a3'
    insert a select 4,'a4'
    insert a select 5,'a5'
    insert a select 6,'a6'
    insert a select 7,'a7'
    insert a select 8,'a8'
    insert a select 9,'a9'
    insert a select 10,'a10'create table  b(id int,itemid int)
    insert b select 1,3
    insert b select 2,4
    select a.*from a,b where a.itemid=b.itemid union all
    select a.* from a where a.itemid not in (select itemid from b)
    /*
    3 a3
    4 a4
    1 a1
    2 a2
    5 a5
    6 a6
    7 a7
    8 a8
    9 a9
    10 a10
      

  3.   

    不能用left join,要用full join。