一个sql查询和排序语句,帮帮我吧

来源:百度知道 编辑:UC知道 时间:2024/06/24 08:36:04
目前有两个表,如table_archives ,table_comment(用户评论).table_archives的字段有typeid,title,writer,pubtime(发布时间)等。table_comment的字段有:username,typeid,title,message,senttime(发送时间)等。我希望是分别查询到两个表中的数据,并且按照pubtime 和senttime 时间的先后对查询出来的数据进行排序。请问如何做到。。能不能实现呢。。头都大了。把积分都贡献出来了作为回报。希望能帮我解决一下或者给我一个思路也可以,感激不尽。。谢谢!!!!!
具体的要求是。。其实我是想同时查询出数据,,并对数据进行时间先后顺序排序 。。
如查询出:
文章1 2009-2-3 15:00
回复1 2009-2-3 13:20
回复2 2009-2-3 11:10
文章2 2009-2-2 11:00

也就是说谁最新发布的谁就在最前面 ...
希望大家能帮我写一个语句或者思路。。

感谢大家的解答。不过仍然有些问题。。由于表1中的时间字段为pubtime,表二中的时间字段为senttime,所以联合查询后。再根据时间先后的顺序进行排列。。
首先联结问题,因为从两个不同的表中读出的数据及字段都不相同并且时间字段也不相同,表1和表2是可以分别按时间排序的。。但是怎么才能按时间先后他们混合交叉排序呢 所以还需要做一个pubtime和senttime的对比。这个问题不解。。谁来挑战下啊。呵呵。

这是MS_SQL2005版本以上的CTE功能;2000可用嵌套或生成临时表处理.
----------
;with c
as
(select row_number()over(order by pubtime desc) as ID,row=0,pubtime as Date,Flag=0 from table_archives)
,c2
as
(
select * from c
union all
select t2.ID,row_number()over(partition by typeid order by senttime desc) as row,senttime as Date,Flag=1
from table_comment t1 inner join c on t1.typeid=t2.typeid)
select
case Flag when 0 then N'文章'+rtrim(ID) else N'回复'+rtrim(row) end as 显示,Date
from
c
order by ID asc,Flag asc,row asc

可以使用union
union查询结果是一个数据集,它的字段名以第一个select后面的字段列表为准,后面的字段列表需要与第一个的对齐(字段个数与数据类型相同,名称无所谓),union all是保留所有数据,不加all会删除重复的记录。

排序使用order by 字段名 desc/asc
加上asc或不加是按照升序排列
加上desc是按照降序排列

select * from table_archives
union all
select * from table_comment
order by pubtime desc , senttime desc

2段语句

select * from table_archives order by pubti