表A
typeID  NAME
1   AAA
2   BBB
3   CCC
4   DDD
表B
id   title    typeID
1    中国       1
2    美国       3
3    英国       3
4    日本       1我想取出表A的记录 然后再取表B中对应的类型的最大ID的那条记录 应该怎么写? 比如最后的结果是
1   AAA    4   日本   1
2   BBB    null
3   CCC    3   英国   3
4   DDD    null

解决方案 »

  1.   

    select a.typeID ,a.NAME , (select max(id) , title from table_b where typeID = a.typeID group by title) , a.typeID  from table_a a , table_b , b where a.typeID = b.typeID
      

  2.   

    select * from A 
    left join
    B on A.typeID=B.typeiD and B.id in (
    select max(id) as id from B group by typeID)
      

  3.   

    insert A select 1,   'AAA'
    union all select 2,   'BBB'
    union all select 3,   'CCC'
    union all select 4,   'DDD'create table B(id int, title nvarchar(10), typeID int) 
    insert B select 1,    '中国',       1
    union all select 2,    '美国',       3
    union all select 3,    '英国',       3
    union all select 4,    '日本',       1
    select * from A 
    left join
    B on A.typeID=B.typeiD and B.id in (
    select max(id) as id from B group by typeID)--resulttypeID      name id          title      typeID      
    ----------- ---- ----------- ---------- ----------- 
    1           AAA  4           日本         1
    2           BBB  NULL        NULL       NULL
    3           CCC  3           英国         3
    4           DDD  NULL        NULL       NULL(4 row(s) affected)
      

  4.   

    create table ta(typeID int,  NAME varchar(10))
    insert ta select 1 ,  'AAA'
    union all select 2 ,  'BBB'
    union all select 3 ,  'CCC'
    union all select 4 ,  'DDD'
    create table tb(id int,  title varchar(10),    typeID int)
    insert tb select 1 ,   '中国'       ,1
    union all select 2 ,   '美国'       ,3
    union all select 3 ,   '英国'       ,3
    union all select 4 ,   '日本'       ,1select a.*,b.* from ta a
    left join 
    (select b.* from tb b
    inner join
    (select max(id) mi from tb group by typeid) c
    on mi=id
    ) b
    on b.typeid=a.typeid
    drop table ta,tb
      

  5.   

    或select a.*,b.* from ta a
    left join tb b
    on b.typeid=a.typeid
    where not exists(select 1 from tb where typeid=b.typeid and id>b.id)