mc2cd 2010-10-11 22:32
浏览 224
已采纳

新手疑问 mysql查询问题

和普通查询 文章的回复数 差不多
create table articles(
id int(11) primary key not null,
title varchar(255) not null,
content text not null
)
create table comments(
id int(11) primary key not null,
articleid int(11) not null,
content text not null
)

insert into articles values(1,'article1','content1');
insert into articles values(2,'article2','content2');
insert into articles values(3,'article3','content3');

insert into comments values(2,2,'reply2');
insert into comments values(3,3,'reply3');

我想查出每篇article的回复数
我的sql是
select a.id,count(c.id) from articles a left join comments c on c.articleid=a.id;
这样查询的结果是:
a.id count(c.id)
2 1
3 1

但是我要的结果是
a.id count(c.id)
1 0
2 1
3 1

我试过这条sql:
select a.id,count(c.id) from articles a left join comments c on c.articleid=a.id group by a.id;
可以得到我想要的结果 但是还有疑问就是
以后数据量大了 我只想查出前十条 这样会不会有效率问题
或是还有别的好方法 或者更改表的结构 前提是mysql

  • 写回答

1条回答 默认 最新

  • u010804832 2010-10-12 08:32
    关注

    [code="sql"]select a.id, ifnull(c.count, 0) from articles a left join (select articleid, count(*) count from comments group by articleid) c on c.articleid=a.id[/code]

    这样效率肯定是低的,每次查询都要group by和join

    可以给articles标增加一个comment_count字段,默认为0,每次有comment增加时,执行一把

    [code="sql"]alter table articles add comment_count int(11) default 0[/code]

    [code="sql"]update articles set comment_count = comment_count + 1 where id = your_article_id[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler