我有以下关于生产的表格以及相应的记录数,
- 人数计数= '565367'
- 捐助者计数= '556325'
- telerec_recipients count= '115147'
- person_addresses count= '563183'
- person_emails count= '106958'
- person_phones count= '676474'
- person_sms count= '22275'
在 UI 端,我想通过应用一些连接或左连接来显示一些数据,最后通过分组、排序和分页生成一个 json 响应。
因此,为了实现这一目标,我尝试了两种方法,一种是创建连接查询的 View 文件,并在 Controller 内应用 where、group by 和 order by 子句,第二种是直接触发 laravel 语法我的 Controller 中的连接数。
因为我的所有表中都有大数据,所以连接查询效果很好,但是当涉及到 group by 语句时,执行时间会很长。
帮助我优化或加快此过程。
我的示例查询是:
SELECT people.id as person_id,donors.donor_id,telerec_recipients.id as telerec_recipient_id,people.first_name,people.last_name,people.birth_date,
person_addresses.address_id,person_emails.email_id,person_phones.phone_id,person_sms.sms_id
FROM `people`
inner join `donors`
on `people`.`id` = `donors`.`person_id`
left join `telerec_recipients`
on `people`.`id` = `telerec_recipients`.`person_id`
left join `person_addresses`
on `people`.`id` = `person_addresses`.`person_id`
left join `person_emails`
on `people`.`id` = `person_emails`.`person_id`
left join `person_phones`
on `people`.`id` = `person_phones`.`person_id`
left join `person_sms`
on `people`.`id` = `person_sms`.`person_id`
GROUP BY `people`.`id`, `telerec_recipients`.`id`
ORDER BY `last_name` ASC LIMIT 25 offset 0;
解释结果:
最佳答案
问题是MySQL在donors
表上使用了错误的索引,您需要指示MySQL使用强制索引
index hint改为使用主键
。
说明
从解释的输出中可以清楚地看出,sg 的 donors
表确实出了问题,因为您可以在额外的列中看到 using temporing, using filesort
。
key
列告诉您 MySQL 在 donors.donor_id
字段上使用唯一索引。但是,donor_id
字段不会在查询中的任何地方用于加入/分组/过滤目的。 donors.person_id
字段在连接中使用。由于donors
表的主键位于person_id
字段上,因此mysql 应该使用它进行连接。 强制索引
索引提示告诉MySQL您坚信应该使用某个索引。
注1: 您有多个重复索引。删除所有重复项,它们只会减慢您的系统速度。
注2:
我认为您的查询违反了sql标准,因为选择列表中的字段既不在分组依据列表中,也不是聚合函数(例如sum()
)的主题,也不是功能依赖的在分组字段上。在 MySQL 中,在某些 sql 模式设置下,允许运行此类查询,但它们可能不会产生与您想要的完全相同的输出。
关于MySQL、PHP Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39830031/