开发者

Converting datetime to date

开发者 https://www.devze.com 2023-01-27 13:12 出处:网络
I have indexes on tbl1.date and tbl2.datetime. When I do the following: EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON tbl2.datetime = tbl1.date

I have indexes on tbl1.date and tbl2.datetime. When I do the following:

EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON tbl2.datetime = tbl1.date

tbl2.datetime index gets used (as expected)

Obviously, I need to convert tbl2.datetime to a date in order for the SELECT statement to work in real life. However, doing so results in none of the indexes getting used:

EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON DATE(tbl2.date) = tbl1.date

What am I missing?

UPDATE: I've tried something开发者_运维问答 like this but keep getting syntax error

"#1064.... check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM tbl1 LEFT JOIN tbl2 ON DATE( SELECT * FROM (SELECT DISTINCT datetime FROM tbl2.datetime) as tem' at line 1"

EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON DATE( SELECT * FROM (SELECT DISTINCT          
datetime FROM tbl2.datetime) as tempTable ) = quotes.GOOG.date


What am I missing?

Nothing - you can't alter the data or data type and expect to be able to use the index.

While being altered for the comparison, there's no link between the value in the index and the value you want/need to use. The only option is to store the value in a way that doesn't require the alteration if you want to see an index get used.


Interesting question. As a workaround I tried to isolate the DATETIME on one hand of the JOIN condition...

EXPLAIN SELECT * 
FROM tbl1
LEFT JOIN tbl2 ON tbl2.datetime
BETWEEN CONCAT( tbl1.date,  ' 00:00:00' ) AND CONCAT( tbl1.date,  ' 23:59:59' )

FWIW, it was a FAIL.

0

精彩评论

暂无评论...
验证码 换一张
取 消