問題:
          在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 閱讀(459) 評論(0)  編輯  收藏 所屬分類: 心得體會
           
          主站蜘蛛池模板: 仙游县| 蒙自县| 舟山市| 三明市| 静安区| 景谷| 香港| 岐山县| 蓬莱市| 中宁县| 饶阳县| 松阳县| 九龙县| 印江| 庐江县| 安乡县| 额敏县| 南康市| 华蓥市| 吉木萨尔县| 无为县| 台北市| 台东县| 板桥市| 颍上县| 若羌县| 乌兰县| 五峰| 新和县| 梅河口市| 葫芦岛市| 海盐县| 佛坪县| 象山县| 甘肃省| 石城县| 宁阳县| 游戏| 当涂县| 道真| 阿克苏市|