问题:
在BBS中,content 和  review 两张表,其中content 记录的是 帖子信息(topic_id,topic_title,topic_content等字段),review 表中记录的是回帖的信息,(review_id,topic_id等字段)在 求一SQL语句,其中topic_id和review_id都是自动增加,现在要求查询出有最新回复的帖子的信息,同时要求有多个回复的一个帖子的主题只能显示一次,能用一个SQL语句搞定吗?数据库是MYSQL 求高手指点下

回答:
select t.id,t.title,t.content,r.newposttime from topic as t inner join (select max(posttime) as newposttime, topicid from review group by topicid) as r on t.id=r.topicid
 
//测试
create table topic(
  id int primary key identity(1,1),
  title varchar(128),
  content text
)

insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')
insert into topic(title,content) values('title1','content1')


create table review(
  id int primary key identity(1,1),
  topicid int references topic(id),
  content text,
  posttime datetime default getdate()
)

insert into review(topicid,content) values(1,'reice1')
insert into review(topicid,content) values(1,'reice1')
insert into review(topicid,content) values(2,'reice1')
insert into review(topicid,content) values(2,'reice1')
insert into review(topicid,content) values(2,'reice1')
insert into review(topicid,content) values(3,'reice1')
insert into review(topicid,content) values(3,'reice1')
insert into review(topicid,content) values(3,'reice1')
insert into review(topicid,content) values(3,'reice1')
insert into review(topicid,content) values(4,'reice1')

select t.id,t.title,t.content,r.newposttime from topic as t inner join (select max(posttime) as newposttime, topicid from review group by topicid) as r on t.id=r.topicid

这些是测试数据,sqlserver2000测试通过

posted on 2006-09-28 18:49 pear 阅读(442) 评论(0)  编辑  收藏 所属分类: 心得体会

只有注册用户登录后才能发表评论。


网站导航: