php - mysql查询优化左连接

标签 php mysql sql

我正在使用以下 mysql 查询来获取一些所需的结果,但问题是它需要更多时间。目前此查询的执行时间为 7456 毫秒,这对于我的项目来说是 Not Acceptable ,我想优化此查询有什么想法吗?

 SELECT *, DATEDIFF(NOW(),ticketstatus_tbl.updation_date) AS problem_age,images_tbl.image_path
            FROM ticketstatus_tbl 
            LEFT JOIN question_tbl ON ticketstatus_tbl.question_id = question_tbl.question_id 
            LEFT JOIN ticketing_tbl ON ticketstatus_tbl.related_ticket_id = ticketing_tbl.ticket_id
            LEFT JOIN department_tbl ON question_tbl.question_dept = department_tbl.department_id
            LEFT JOIN branch_tbl ON ticketstatus_tbl.branch_id = branch_tbl.id
            LEFT JOIN images_tbl ON images_tbl.question_id = ticketstatus_tbl.question_id and images_tbl.branch_id = ticketstatus_tbl.branch_id
            WHERE (ticketstatus_tbl.ticket_status NOT IN ('Close')
            AND question_tbl.is_active_question = 1
            AND ticketstatus_tbl.display_status = '1'
            AND ticketstatus_tbl.flag_color = 'Yellow'
            AND department_tbl.department_name = 'Admin')order by ticket_number ASC LIMIT 0 ,5

谢谢

最佳答案

首先,您不需要所有的左外连接,因为您的where子句正在撤消其中的大部分。我的猜测是所有都可以变成内部联接,但至少:

SELECT *, DATEDIFF(NOW(),ticketstatus_tbl.updation_date) AS problem_age,images_tbl.image_path
FROM ticketstatus_tbl 
            JOIN question_tbl ON ticketstatus_tbl.question_id = question_tbl.question_id 
            LEFT JOIN ticketing_tbl ON ticketstatus_tbl.related_ticket_id = ticketing_tbl.ticket_id
            JOIN department_tbl ON question_tbl.question_dept = department_tbl.department_id
            LEFT JOIN branch_tbl ON ticketstatus_tbl.branch_id = branch_tbl.id
            LEFT JOIN images_tbl ON images_tbl.question_id = ticketstatus_tbl.question_id and images_tbl.branch_id = ticketstatus_tbl.branch_id
WHERE ticketstatus_tbl.ticket_status NOT IN ('Close')
            AND question_tbl.is_active_question = 1
            AND ticketstatus_tbl.display_status = '1'
            AND ticketstatus_tbl.flag_color = 'Yellow'
            AND department_tbl.department_name = 'Admin'
order by ticket_number ASC LIMIT 0 ,5;

其次,您正在对ticketstatus_tbl进行过滤。您应该在 ticketstatus_tbl(display_status, flag_color, Ticket_status, Question_id) 上有一个复合索引。如果可以的话,将 ticket_status not in ('Close') 更改为肯定语句:ticket_status in (Open, 'In Progress', ...) 。这使得索引的使用更加容易。

这是一个开始。

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

相关文章:

php - 将多个 MySQL 语句合并为一个

MySql 从不同的随机类别中获取随机元素

sql - SQL中,去除相邻的重复行并进行时间计算

php - 将聊天记录存储在单个数据库表中

php - 使用excel表创建树结构的算法

php - 无法解释的 PHP 错误(内部服务器错误 500)

php - 无法使用api将数据插入android中的数据库

php - CodeIgniter Active Record 返回 Mysql 数据类型而不仅仅是字符串

mysql - 选择并加入 mysql 中的表

c# - 带有 Lambda 表达式的 LINQ - 连接、分组依据、求和和计数