是这样的 有个讨论模块 发帖主表 A
-----------------------------
A.id A.文章标题 A.发帖时间
回贴表 B
-----------------------------------------
B.id 主表ID(A.id)B.回复内容 B.回复时间 B.回复人
现在想通过SQL语句实现这样的功能:在列表页中如何显示最后回复时间,回复人和文章标题?
谢谢大家的帮忙
-----------------------------
A.id A.文章标题 A.发帖时间
回贴表 B
-----------------------------------------
B.id 主表ID(A.id)B.回复内容 B.回复时间 B.回复人
现在想通过SQL语句实现这样的功能:在列表页中如何显示最后回复时间,回复人和文章标题?
谢谢大家的帮忙
from A join B
on A.id=B.id
group by B.回复人,A.文章标题
文章标题,
(select top 1 回复人 from B where id=A.id order by 回复时间 desc) as 回复人,
(select top 1 回复时间 from B where id=A.id order by 回复时间 desc)as 回复时间
from A
文章标题,
(select top 1 回复人 from B where id=t.id order by 回复时间 desc) as 回复人,
(select top 1 回复时间 from B where id=t.id order by 回复时间 desc)as 回复时间
from A as t
declare @a table(id int identity(1,1),文章标题 varchar(20),发帖时间 datetime)
insert @a
select 'a','2007-10-01'
union all
select 'b','2007-10-02'declare @b table(id int identity(1,1),aid int,回复内容 varchar(20),回复时间 datetime,回复人 varchar(20))
insert @b
select 1,'第一封帖的回复','2007-10-09','user1'
union all
select 1,'第一封帖的回复','2007-10-10','user2'
union all
select 1,'第一封帖的回复','2007-10-11','user3'
union all
select 2,'第二封帖的回复','2007-10-10','user3'
union all
select 2,'第二封帖的回复','2007-10-11','user2'
union all
select 2,'第二封帖的回复','2007-10-12','user1'
select a.文章标题,b.回复时间,b.回复人 from @b b,@a a ,(select aid,max(回复时间) 回复时间 from @b b group by aid) c
where a.id=b.aid and a.id=c.aid and b.回复时间=c.回复时间
/*(所影响的行数为 2 行)
(所影响的行数为 6 行)文章标题 回复时间 回复人
-------------------- ------------------------------------------------------ --------------------
b 2007-10-12 00:00:00.000 user1
a 2007-10-11 00:00:00.000 user3(所影响的行数为 2 行)
*/
文章标题,
(select top 1 回复人 from B where id=t.id order by 回复时间 desc) as 回复人,
(select top 1 回复时间 from B where id=t.id order by 回复时间 desc)as 回复时间
from A as t其中的where id=t.id order by 的id指的是那个表的id,我做了怎么还是不对呀?能否把语句写完整?
这样做就正确了:
select
文章标题,
(select top 1 回复人 from B where B.id=t.id order by 回复时间 desc) as 回复人,
(select top 1 回复时间 from B where B. id=t.id order by 回复时间 desc)as 回复时间
from A as t