0

我有一个相当优化的查询。但是,当我添加此连接时,它会将查询增加 70 秒。我能看到的最大问题是我必须根据同一日期比较两个日期时间。换句话说,2013-01-01 8:37am 必须加入到 2013-01-01 9:01am。所以,我首先将两者都转换为日期,然后比较它们。

有没有更快的方法可以在不修改表的情况下做到这一点?我已经为下面连接中的所有字段添加了索引。

LEFT JOIN ins ON 
DATE(ins.ins_date) = DATE(r.date) 

更新:最终尝试了一些不同的技巧,例如从日期中减去几个小时并直接比较日期将利用至少一个索引,并且向连接添加更多标准有助于减少它尝试执行 DATE() 的记录上的操作。我相信下面的海报也有一个有效的建议,即为日期创建一个单独的字段,但我无法针对这种情况修改表格,但我将来可能会尝试这样做。

4

1 回答 1

1

In the join statement you showed us, you are transforming the datetime (into a plain date) in order to compare it. That means that the database engine will have to examine every *single* record in the table to see if they meet the criteria you're after. Even if you have an index on ins_date, the engine will not be able to use it to find the records you're after.

See if you can re-craft the query to use the columns in their native form (i.e. without any transformation applied to them). If you have to apply some kind of transformation to a column in order to do a join or filter, try to do it only to the tiniest table in that join, to reduce the number of records that have to be retrieved and transformed.

If you can, and this is a query that runs more than only occasionally, see if you can redefine the columns you are using to DATE rather than DATETIME types. If you need the time portion of the DATETIME value in your application(s), then see if you can maintain a ghost DATE column with only the DATE portion of that DateTime value (this can be maintained by the insert queries, or by a trigger).

于 2013-07-28T05:36:54.890 回答