mysql按顺序通过desc获取最新记录而不使用子查询

时间:2014-06-18 10:30:26

标签: mysql sql

我试图通过以下查询获得结果,但需要大约2分钟来检索

SELECT * 
FROM customer e 
WHERE e.id=324 
AND e.g_id IN('x133fv','be6544','e992170','93611c') 
and e.enrol_id = 
(
 select e1.enrol_id 
 from customer e1 
 WHERE e1.id=324 
 AND e1.g_id=e.g_id 
 ORDER BY update_time DESC, posted_time DESC, enrol_id DESC 
 LIMIT 1
)

我有(g_id,id)

的索引

有没有其他方法可以通过JOIN获得结果?

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT *
FROM customer e
WHERE e.id = 324 AND
      e.g_id IN ('x133fv','be6544','e992170','93611c') and
      e.enrol_id = (select e1.enrol_id
                    from customer e1
                    WHERE e1.id=324 AND e1.g_id=e.g_id
                    ORDER BY update_time DESC, posted_time DESC, enrol_id DESC
                    LIMIT 1
                   )

您可以使用索引提高性能。我建议:customer(id, g_id, update_time, posted_time, enrol_id)