1

我想使用 检索两个表的最新记录UNION,它返回数据,但不返回最新记录,即使使用ORDER BY. 这是我的查询:

    SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName 
FROM TheaterNews 
    UNION
    SELECT TOP(3) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName  
FROM MoviesNews
    ORDER BY 3 DESC

这是查询的输出:
使用 UNION 输出

但最新的记录TheaterNews是更新的:

SELECT  OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName 
FROM TheaterNews 
ORDER BY NewsCreationDate DESC

TheatreNews 表的最新记录

我怎样才能解决这个问题?即使用另一种方法。

4

4 回答 4

7

order by应用于联合的整个结果,而不是单独的查询,因此在top结果排序之前应用 。

使用子查询对单独的结果进行排序:

SELECT * FROM (
  SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
  FROM TheaterNews
  ORDER BY 3 DESC
) x
UNION
SELECT * FROM (
  SELECT TOP(3) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
  FROM MoviesNews
  ORDER BY 3 DESC
) y
于 2012-05-31T11:17:18.350 回答
3

因为 top 子句在 order by 子句之前执行。试试这个

  Select * from (SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,       
                    NewsEnglishName 
                 FROM TheaterNews      ORDER BY 3 DESC) as tn
  UNION
  Select * From (SELECT TOP(3)       
                 OwnerID,NewsTitle,NewsCreationDate,NewsEnglishName  
                 FROM MoviesNews     ORDER BY 3 DESC) as mn
  ORDER BY 3 DESC

外部 order by 将对联合结果进行排序

于 2012-05-31T11:18:33.673 回答
2

这应该适用于您的实例。可能是一个粗略的解决方案,但您会得到答案。您可以用@tables 替换#tables。

SELECT TOP(1) 
    OwnerID,
    NewsTitle,
    NewsCreationDate,
    NewsEnglishName 
into
    #Table1
FROM 
    TheaterNews 
ORDER BY 3 DESC

SELECT TOP(3) 
    OwnerID,
    NewsTitle,
    NewsCreationDate,
    NewsEnglishName
into
    #Table2
FROM 
    MoviesNews
ORDER BY 3 DESC

select * from #Table1
union
select * from #Table2

drop table #Table1
drop table #Table2
于 2012-05-31T11:48:58.550 回答
1

试试这个:

Select * From ( SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName 
    FROM TheaterNews ORDER BY NewsCreationDate DESC) as tempA
        UNION
     Select * From  ( SELECT TOP(3) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName  
    FROM MoviesNews ORDER BY NewsCreationDate DESC) as tempB
于 2012-05-31T11:16:38.853 回答