优化SQL查询-从第二个表中有多行的两个表中获取记录

时间:2019-07-03 10:51:26

标签: mysql

我正在尝试从两个表中获取记录。表 Spa 和表 spa_meta

我的Sql查询是

 SELECT spa_1.id as sid, spa_1.title, spa_1.doc_type, spa_1.inventory_id, inventory.unit_no as unit_no,spa_1.spa_status as spa_status, 

spa_meta.*

    FROM spa_meta

    JOIN (
       SELECT spa.*, (SELECT MAX(created_at) FROM spa_meta WHERE spa_meta.spa_id = spa.id) as max_date FROM spa ) 

AS spa_1 ON spa_1.max_date = spa_meta.created_at AND spa_1.id = spa_meta.spa_id

    LEFT JOIN inventory ON spa_1.inventory_id = inventory.id  

    where spa_1.spa_status LIKE "completed%"

     group by spa_meta.spa_id

此查询可按要求运行,但在10秒钟以上即可呈现数百条记录。 我想对此进行优化。

表定义

SPA http://prntscr.com/oa30t6

SPA_META http://prntscr.com/oa2zq7

目标 SPA 表中有唯一的记录,在 SPA_META 中,SPA中具有相同ID的多个结果。那就是spa.id = spa_meta.spa_id

我想从两个表中获取结果,其中日期时间条目为Max(created_at),且spa_meta表中的日期数据与spa表中的一行数据组合在一起。

问题:如何减少此查询的执行时间,或者是否有其他解决方案可从元表中创建整行的地方(created_at列应为Max(created_at))?

1 个答案:

答案 0 :(得分:1)

尝试使用JOIN而不是子查询来获取max_date,并仔细检查索引:

    SELECT spa_1.id as sid, spa_1.title, spa_1.doc_type, spa_1.inventory_id, inventory.unit_no as unit_no,spa_1.spa_status as spa_status, 
    spa_meta.*
FROM spa_meta
INNER JOIN (
   SELECT s.spa_id, MAX(s.title) AS title, MAX(s.doc_type) AS doc_type, MAX(s.inventory_id) AS inventory_id,
      MAX(s.spa_status) AS spa_status,
      MAX(sm.created_at) as max_date 
   FROM spa s
   INNER JOIN spa_meta sm
   ON s.spa_id=sm.spa_id
   WHERE s.spa_status LIKE 'completed%'
   GROUP BY s.spa_id) AS spa_1
ON spa_1.max_date = spa_meta.created_at
AND spa_1.id = spa_meta.spa_id
LEFT JOIN inventory
ON spa_1.inventory_id = inventory.id;