Mysql php计数内部联接的数量使用子查询可以更快地工作

Mysql php计数内部联接的数量使用子查询可以更快地工作,php,mysql,sql-server,join,Php,Mysql,Sql Server,Join,两个表,第一个是用户,第二个是帖子,表帖子结构是id,body,parent\u id,user\u id,在该表中插入所有帖子时,parent\u id为null,如果是注释,则parent\u id设置为帖子id 我试图做的是加入用户表——获取用户详细信息——并统计每篇文章的评论数 我试着问了几个问题 select p.id, users.id as 'from_id', users.fullname as 'from_fullname',

两个表,第一个是用户,第二个是帖子,表帖子结构是
id,body,parent\u id,user\u id
,在该表中插入所有帖子时,parent\u id为null,如果是注释,则parent\u id设置为帖子id

我试图做的是加入用户表——获取用户详细信息——并统计每篇文章的评论数

我试着问了几个问题

select  p.id,
        users.id as 'from_id',
        users.fullname as 'from_fullname',
        users.role as 'from_role',
        users.picture as 'from_picture',
        p.body,
        p.time_posted as 'time_posted',
        p.attachment,
        p.parent_id,
        count(c.id) as counts
from 
    wall p
join   
    users on users.id = p.user_id
left join 
    wall c on c.parent_id = p.id
where 
    p.class_id = 8 and p.parent_id is null
group by 
    p.id
order by
    `counts` ---->EXPLAIN RESULTS

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  p   ref PRIMARY,parent_id,class_id,user_id  parent_id   5   const   49920   Using index condition; Using where; Using temporary; Using filesort
1   SIMPLE  users   eq_ref  PRIMARY PRIMARY 4   ischool.p.user_id   1   NULL
1   SIMPLE  c   ref parent_id   parent_id   5   ischool.p.id    49920   Using index
这一次平均需要2.7秒左右才能完成

而我的第二次尝试

select  p.id,
        users.id as 'from_id',
        users.fullname as 'from_fullname',
        users.role as 'from_role',
        users.picture as 'from_picture',
        p.body,
        (select count(*) from wall where parent_id= p.id ) as comments_count,
        p.time_posted as 'time_posted',
        p.attachment,
        p.parent_id
from 
    wall p
left join 
    users on users.id = p.user_id
where 
    p.class_id = 8 and p.parent_id is NULL
order by 
    p.id DESC; --->Explain results

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY p   ref parent_id,class_id  parent_id   5   const   49920   Using where
1   PRIMARY users   eq_ref  PRIMARY PRIMARY 4   ischool.p.user_id   1   NULL
2   DEPENDENT SUBQUERY  wall    ref parent_id   parent_id   5   ischool.p.id    49920   Using index
完成此查询需要1.4秒

假设我使用MYSQL innodb,每个id列上都有索引

  • 那么,有没有更好的方法来获取帖子和评论数量呢
  • 为什么子查询比join快近2倍

  • 基本上,联接比子查询更快。通常,新开发人员更喜欢使用子查询

    查询的执行计划可能会影响性能。几乎所有情况下,查询联接都比子查询快

    基本区别在于子查询执行查询并加载所有数据,然后基于这些数据执行另一个查询

    连接是所有表,所有表都加载了数据,所以它可以快速执行查询

    在您的查询中,如果您想显示为什么子查询比join快,请使用“explain”命令来显示查询是如何实际执行的

    以下链接可能有助于理解概念:

    任何时候,如果您想了解查询性能,都必须从解释开始,并为所有相关表提供适当的DDL。@草莓yp做到了这一点,但我不完全理解解释返回的内容,我将使用结果编辑问题。当然,大多数情况下,联接将比子查询更快,尤其是内部联接,在子查询中,mysql将获取每个主查询迭代中的所有行,然后在以后的主查询中对其进行过滤,而join query直接过滤行并仅获取通过过滤的行。还要注意,索引越多并不意味着性能越快,但索引越好。ehhm,我已经做了,并发布了有问题的解释结果。我看不出你是如何回答任何问题的。这太简单了,没有任何用处true@Strawberry/Zalaboza:你在同一时间发了同一个帖子,你没有权利不被否认,对我的回答投反对票,这不是我的错。如果你不能像我一样解释事情,那不是我的错。我已经解释过你想做什么简而言之,真实地对待真理。