日期:2014-05-16  浏览次数:20955 次

合并查询后排序的问题
有两张表,我想把它们查出的结果放到一起,然后再按时间进行排序,最后取前10项,怎末做?
这是查询语句
SELECT PostsId AS id, PostsTitle AS Title,PostsDate AS SendDate, 1 AS Type
FROM BbsPosts
WHERE (PostsUserId = 'admin' AND IsDeleted=False ) 
UNION ALL
SELECT ReplyId AS id, ReplyTitle AS Title,ReplyDate as SendDate, 2 AS type
FROM BbsReply
WHERE (ReplyUserId = 'admin' AND IsDeleted=False )
可以吧需要的结果都查出来,然后怎么排序和取前10行?
表结构是:
BbsPosts:
PostsId PostsTitle PostsDate ....
---------------------------------
和表
BbsReply:
ReplyId ReplyTitle ReplyDate ....
---------------------------------

想要的结构是:
id Title SendDate Type
-----------------------
只要时间最靠后的10项

------解决方案--------------------
SQL code
select top 10 * from (
SELECT   PostsId AS id, PostsTitle AS Title,PostsDate AS SendDate, 1 AS Type
FROM      BbsPosts
WHERE   (PostsUserId = 'admin' AND IsDeleted=False ) 
UNION ALL
SELECT   ReplyId AS id, ReplyTitle AS Title,ReplyDate as SendDate, 2 AS type
FROM      BbsReply
WHERE   (ReplyUserId = 'admin' AND IsDeleted=False )
)
order by SendDate desc

------解决方案--------------------
如果是按 SendDate 排序
select top 10 * from (
SELECT PostsId AS id, PostsTitle AS Title,PostsDate AS SendDate, 1 AS Type
FROM BbsPosts
WHERE (PostsUserId = 'admin' AND IsDeleted=False ) 
UNION ALL
SELECT ReplyId AS id, ReplyTitle AS Title,ReplyDate as SendDate, 2 AS type
FROM BbsReply
WHERE (ReplyUserId = 'admin' AND IsDeleted=False ) )
order by SendDate desc