在 MySql 中,我有一个 UNION 查询,它需要很长时间才能执行。查询看起来像
(SELECT id, X, Y , date FROM TABLE WHERE date in (SELECT MIN(date) FROM TABLE WHERE flag = 0 AND id = ? AND date BETWEEN ? AND ?) and id = ? and flag=0 ORDER BY id DESC LIMIT 1)
UNION
(SELECT id, X, Y , date FROM TABLE WHERE date in (SELECT MAX(date) FROM TABLE WHERE flag = 0 AND id = ? AND date BETWEEN ? AND ?) and id = ? and flag = 0 ORDER BY id DESC LIMIT 1)
问题是为了获得上述查询的最佳性能,需要索引哪些列以及为什么?
id - type int
date - type datetime
flag - type tinyint(4)