首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Access >

合并查询后排序的有关问题

2012-02-11 
合并查询后排序的问题有两张表,我想把它们查出的结果放到一起,然后再按时间进行排序,最后取前10项,怎末做?

合并查询后排序的问题
有两张表,我想把它们查出的结果放到一起,然后再按时间进行排序,最后取前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 TypeFROM      BbsPostsWHERE   (PostsUserId = 'admin' AND IsDeleted=False ) UNION ALLSELECT   ReplyId AS id, ReplyTitle AS Title,ReplyDate as SendDate, 2 AS typeFROM      BbsReplyWHERE   (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

热点排行