問(wèn)題:
在BBS中,content 和? review 兩張表,其中content 記錄的是 帖子信息(topic_id,topic_title,topic_content等字段),review 表中記錄的是回帖的信息,(review_id,topic_id等字段)在 求一SQL語(yǔ)句,其中topic_id和review_id都是自動(dòng)增加,現(xiàn)在要求查詢出有最新回復(fù)的帖子的信息,同時(shí)要求有多個(gè)回復(fù)的一個(gè)帖子的主題只能顯示一次,能用一個(gè)SQL語(yǔ)句搞定嗎?數(shù)據(jù)庫(kù)是MYSQL 求高手指點(diǎn)下
回答:
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
?
//測(cè)試
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
這些是測(cè)試數(shù)據(jù),sqlserver2000測(cè)試通過(guò)
只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。 | ||
![]() |
||
網(wǎng)站導(dǎo)航:
博客園
IT新聞
Chat2DB
C++博客
博問(wèn)
管理
|
||
相關(guān)文章:
|
||