sql
我现在有6个表,表中有datetime属性的date,现在我想要的是选取每个表中的date最大的记录,并且把所有检索到的6条记录汇总并排序。
select sort,[name] from
( select * from
(select top 1 sort,[name],date as intro from Intro order by date desc)
union all
select * from
(select top 1 sort,[name],date as news from News order by date desc)
union all
select * from
(select top 1 sort,[name],date as teach from Teach order by date desc)
union all
select * from
(select top 1 sort,[name],date as inside from Inside order by date desc)
union all
select * from
(select top 1 sort,[name],date as outside from Outside order by date desc)
union all
select * from
(select top 1 sort,[name],date as help from Help order by date desc)
order by date)提示union附近有语法错误,望指正!
sqlunion

解决方案 »

  1.   

    union all只可以有一个order by
      

  2.   

    select sort,[name] from
        (    select * from
            (SELECT * FROM intro a
    WHERE EXISTS (SELECT 1 FROM (SELECT MAX(date) date  FROM info ) b WHERE  a.date=b.date)
    UNION ALL 
    .....下面把表名改了就行)
        order by date)
      

  3.   


    select sort,[name] from
    ( select * from
    (select top 1 sort,[name],date as intro from Intro )
    union all
    select * from
    (select top 1 sort,[name],date as news from News )
    union all
    select * from
    (select top 1 sort,[name],date as teach from Teach )
    union all
    select * from
    (select top 1 sort,[name],date as inside from Inside )
    union all
    select * from
    (select top 1 sort,[name],date as outside from Outside )
    union all
    select * from
    (select top 1 sort,[name],date as help from Help )
    order by date DESC)
      

  4.   

    哦,明白了,找出表中最大值,然后根据最大值查询该记录,最后6个表的查询汇总再排序。是这个思路吧?嗯,union /union all只有最后才用order by
      

  5.   

    select sort,[name],date from
        (    select * from
            (select top 1 sort,[name],date as intro from Intro )
            union all
            select * from
            (select top 1 sort,[name],date as news from News )
            union all
            select * from
            (select top 1 sort,[name],date as teach from Teach )
            union all
            select * from
            (select top 1 sort,[name],date as inside from Inside )
            union all
            select * from
            (select top 1 sort,[name],date as outside from Outside )
            union all
            select * from
            (select top 1 sort,[name],date as help from Help )
        )A
        order by date DESC
      

  6.   

    哦,明白了,找出表中最大值,然后根据最大值查询该记录,最后6个表的查询汇总再排序。是这个思路吧?嗯,union /union all只有最后才用order by
    多谢版主!