問題:
          在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 閱讀(451) 評論(0)  編輯  收藏 所屬分類: 心得體會
           
          主站蜘蛛池模板: 藁城市| 盘山县| 万载县| 临西县| 香格里拉县| 湛江市| 集贤县| 惠州市| 正宁县| 额尔古纳市| 花莲市| 平遥县| 黄大仙区| 拜城县| 旬邑县| 阜阳市| 怀仁县| 保定市| 宜宾县| 盐城市| 温宿县| 淮滨县| 中宁县| 醴陵市| 东乌| 平阳县| 九龙坡区| 汨罗市| 平果县| 阳高县| 绥宁县| 锦屏县| 吉木乃县| 龙井市| 无棣县| 安陆市| 武胜县| 红安县| 米林县| 清原| 潼关县|