mysql - 优化 MySql 查询

标签 mysql performance query-optimization sql-optimization

我想知道是否有优化此查询的方法:

SELECT
    jdc_organizations_activities.*,
    jdc_organizations.orgName, 
    CONCAT(jos_hpj_users.firstName, ' ', jos_hpj_users.lastName) AS nameContact  
FROM jdc_organizations_activities
LEFT JOIN jdc_organizations ON jdc_organizations_activities.organizationId =jdc_organizations.id
LEFT JOIN jos_hpj_users ON jdc_organizations_activities.contact = jos_hpj_users.userId
WHERE jdc_organizations_activities.status LIKE 'proposed'  
ORDER BY jdc_organizations_activities.creationDate DESC LIMIT 0 , 100 ;

Tables Info

现在当我看到查询日志时:

 Query_time: 2  
 Lock_time: 0  
 Rows_sent: 100  
 Rows_examined: **1028330**

查询配置文件:

enter image description here

2) 我是否应该在表上放置索引,因为这些表上会有很多插入和更新。

来自 Tizag 教程:

Indexes are something extra that you can enable on your MySQL tables to increase performance,cbut they do have some downsides. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.

添加索引并删除 lower() 、分组依据和通配符后更新

时间:0.855ms

enter image description here

最佳答案

在以下位置添加索引(如果没有):

表:jdc_organizations_activities

  • creationDate 上的简单索引
  • 关于状态的简单索引
  • organizationId 上的简单索引>
  • 关于联系人的简单索引

并通过删除对函数 LOWER() 的调用并使用 =LIKE 来重写查询。这取决于您为此表定义的排序规则,但如果它是不区分大小写的排序规则(如 latin1),它仍会显示相同的结果。详情请见 MySQL docs: case-sensitivity

SELECT a.*
     , o.orgName
     , CONCAT(u.firstName,' ',u.lastName) AS nameContact  

FROM jdc_organizations_activities AS a
  LEFT JOIN jdc_organizations AS o
    ON a.organizationId = o.id 
  LEFT JOIN jos_hpj_users AS u
    ON a.contact = u.userId

WHERE a.status LIKE 'proposed'     --- or (a.status = 'proposed')

ORDER BY a.creationDate DESC 
LIMIT 0 , 100 ;

如果您发布执行计划(就像现在这样)以及这些更改之后,那就太好了。


更新

(status, creationDate) 上的复合索引可能更适合(如 Darhazer 所建议的)此查询,而不是简单的 (status)。但这是更多的猜测工作。发布计划(在运行 EXPLAIN query 之后)将提供更多信息。

我还假设您已经有(主键)索引:

  • jdc_organizations.id
  • jos_hpj_users.userId

关于mysql - 优化 MySql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6539163/

相关文章:

python - Django 模型计数器

mysql - PDO - 改变旧的 mysql_fetch_object

c++ - 性能:循环中的声明 VS 循环中的重新初始化

performance - SwiftUI ObservableObject CPU 峰值

java - Android NDK 是否为通过套接字发送大 int[] 提供加速?

MySQL 数据库 - 将数据存储在一个表中或使用查找

mysql - 使用group by从mysql选择查询中删除相似的字段

php - 在循环触发时在php中查询但给出一个变量的结果

php - 左连接重复项

MySQL 在商店定位器-Google map 应用程序的分组查询中选择错误的列值