日期:2014-05-18  浏览次数:20455 次

求一SQL语句:按时间排序
是这样的  

有个讨论模块

发帖主表   A
-----------------------------
A.id       A.发帖内容     A.发帖时间


回贴表     B
-----------------------------------------
B.id     主表ID(A.id)   B.回复内容   B.回复时间


现在想通过SQL语句实现这样的功能:在列表页中显示主要A的记录按照最后回复时间或最新发表时间进行排序,即哪个贴是最后被回复了,就排在第一位,哪个贴是最新发表的也是排在前面。


谢谢大家的帮忙

------解决方案--------------------
select A.发帖内容 , A.发帖时间 时间 from a where a.id not in (select b.id from b)
union all
select A.发帖内容 , b.回复时间 时间 from a, b where a.id = b.id
order by 时间 desc
------解决方案--------------------
select A.发帖内容 , A.发帖时间 时间 from a where a.id not in (select b.主表ID from b)
union all
select A.发帖内容 , b.回复时间 时间 from a, b where a.id = b.主表ID
order by 时间 desc

------解决方案--------------------
select
t.*
from
发帖主表A t
order by
isnull((select max(回复时间) from 回贴表B where 主表ID=t.ID order by ),t.发帖时间)
------解决方案--------------------
select
t.*
from
发帖主表A t
order by
isnull((select max(回复时间) from 回贴表B where 主表ID=t.ID order by ),t.发帖时间) DESC
------解决方案--------------------
select A.发帖内容 , A.发帖时间 时间 from a where a.id not in (select b.主表ID from b)
union all
select A.发帖内容 , max(b.回复时间) 时间 from a, b where a.id = b.主表ID group by a.id
order by 时间 desc

------解决方案--------------------
我的最后一个才对.
------解决方案--------------------
select * from
(
select A.id, A.发帖内容 , A.发帖时间
from A
union
select A.id, A.发帖内容 ,B.回复时间
from a inner join b on a.id=b.主表ID) C
ORDER BY 发帖时间
------解决方案--------------------
select distinct a.*,b1.回复时间 as 最后回复时间
from a
join b b1
on a.id = b1.主表ID
and not exsits(
select 1 from b where 主表ID = b1.主表ID and b1.回复时间 < b.回复时间
)
order by 最后回复时间 desc
------解决方案--------------------
老大们都没我写的好,呵呵
------解决方案--------------------
楼上的老大们都写得很好,,,
------解决方案--------------------
--改改
select distinct a.*,isnull(b1.回复时间,a.发帖时间) as 最后回复时间
from a
left join b b1
on a.id = b1.主表ID
and not exsits(
select 1 from b where 主表ID = b1.主表ID and b1.回复时间 < b.回复时间
)
order by 最后回复时间 desc

------解决方案--------------------
declare @a table(id int identity(1,1),发帖内容 varchar(20),发帖时间 datetime)
insert @a
select 'a ', '2007-09-01 '
union all
select 'b ', '2007-08-15 '
declare @b table(id int identity(1,1),aid int,回复内容 varchar(20),回复时间 datetime)
insert @b
select 2, 'bbb ', '2007-09-02 '
union all
select 1, 'aaa ', '2007-09-03 '

select 发帖内容,发帖时间 as 时间 from @a
union all
select 回复内容,回复时间 as 时间 from @b
order by 时间 desc


/*

(所影响的行数为 2 行)


(所影响的行数为 2 行)

发帖内容 时间