2016-10-03 65 views
0

我有以下的生产与记录的相应计数表,MySQL和PHP Laravel

  • 数= '565367'
  • 捐助者数= '556325'
  • telerec_recipients count ='115147'
  • person_addresses count ='563183'
  • person_emails计数= '106958'
  • person_phones计数= '676474'
  • person_sms计数= '22275'

在用户界面上端欲显示由一些数据应用一些连接或左连接,最后通过分组,排序和分页我生成一个JSON响应。因此,为了实现这个目的,我尝试了2种方法,其中一种由创建连接查询的视图文件,并应用在控制器中的where,group by和order by子句,其次通过直接激发我的连接的laravel语法控制器。

因为我在所有表中都有一个大数据,连接查询效果很好,但是当涉及到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; 

的结果的解释:

enter image description here

Donors Table Indexes

+0

请提供解释的结果,直到任何建议的解决方案是纯粹的猜测。 – Shadow

+0

@Shadow,我需要为您提供上述查询的输出吗? –

+0

不,解释的结果。 – Shadow

回答

0

的问题是,MySQL使用了错误的指标上donors表,需要指示MySQL使用force indexindex hint来使用0123改为。

说明

从的输出解释很清楚,SG真的去错donors表,因为你可以在额外栏中看到using temporary, using filesort

key列告诉你MySQL在donors.donor_id字段上使用唯一索引。但是,donor_id字段在用于加入/分组/过滤目的的查询中不在任何地方使用。在连接中使用donors.person_id字段。由于donors表的主键位于person_id字段,因此myql应将其用于联接。force index索引提示告诉MySQL你坚信应该使用某个索引。

注1: 您有多个重复索引。删除所有重复项,它们只会让你的系统变慢。

注意2: 我认为你的查询是针对sql标准的,因为你在选择列表中既不在列表中的字段,也不是聚合函数的主题,例如sum(),在功能上依赖于分组字段。在某些sql模式下的MySQL设置中,这样的查询被允许运行,但它们可能不会产生完全相同的输出。

+0

我修改了符合最好的SQL标准的查询,但它仍然给我延迟的问题。 –

+0

这是我的答案中的一个笔记,而不是主要观点。 – Shadow

+0

问题仍然是一样的,就像我如何摆脱那些使用临时的,使用来自额外列中列出的捐助者索引的filesort。 –