从两个表中选择数据并按日期排序

时间:2011-07-27 18:04:56

标签: sql sql-server select union

我有两个包含数据的表,需要将它们组合在一起并按日期排序。我有以下查询,但工会一直给我一个错误。

SELECT 

AssetTitle,
AssetDate,
AssetTeaser,
AssetLink

FROM pressAssets WHERE AssetType=1 ORDER BY AssetDate ASC

UNION ALL

SELECT

BlogTitle,
BlogDate,
BlogEntry,
BlogLink


FROM

blogTempTable ORDER BY BlogDate ASC, AssetDate ASC;

任何人都可以帮我吗?

4 个答案:

答案 0 :(得分:4)

您的代码不能正常工作。这将为您提供结果集,但日期字段全部合并在一起;在UNION应用后,您无法区分来源。

SELECT 
  Title,
  Date,
  Teaser,
  Link

FROM (
SELECT 

AssetTitle Title,
AssetDate Date,
AssetTeaser Teaser,
AssetLink Link

FROM pressAssets WHERE AssetType=1 

UNION ALL

SELECT

BlogTitle Title,
BlogDate Date,
BlogEntry Teaser,
BlogLink Link


FROM

blogTempTable) T

ORDER BY Date ASC;

答案 1 :(得分:1)

使用子查询:

select *
from
(
    SELECT 

    AssetTitle,
    AssetDate,
    AssetTeaser,
    AssetLink

    FROM pressAssets WHERE AssetType=1 

    UNION ALL

    SELECT

    BlogTitle,
    BlogDate,
    BlogEntry,
    BlogLink


    FROM

    blogTempTable
)a
ORDER BY AssetDate ASC;

答案 2 :(得分:1)

只允许一个ORDER BY用于UNIONed结果集。您无法单独订购这两个查询。

答案 3 :(得分:1)

我想:

Select * from 
(
SELECT AssetTitle as mtitle, AssetDate as mdate, 
AssetTeaser as mtease, AssetLink as mlink
FROM pressAssets 
WHERE AssetType=1
UNION
SELECT BlogTitle as mtitle, BlogDate as mdate,
BlogEntry as mtease, BlogLink, as mlink
FROM blogTempTable
)
ORDER BY mdate

会很接近。

编辑:这与Yuck纠正的答案相同。