問題:
          在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 閱讀(456) 評論(0)  編輯  收藏 所屬分類: 心得體會
           
          主站蜘蛛池模板: 从化市| 文山县| 临澧县| 徐水县| 西畴县| 潜山县| 宁强县| 榆树市| 丹江口市| 孟村| 铜陵市| 黄冈市| 巴楚县| 肃南| 灵丘县| 塔城市| 疏勒县| 宝鸡市| 河池市| 乐安县| 兴和县| 陕西省| 射洪县| 嵩明县| 崇明县| 呼图壁县| 梓潼县| 肃宁县| 永顺县| 华安县| 岗巴县| 佛冈县| 嘉义县| 三亚市| 承德县| 霍山县| 铅山县| 封丘县| 神农架林区| 邢台县| 迁安市|