使用with解決mysql日期匹配及隨機(jī)月份問題
原始sql遇到詭異情況,查詢不到預(yù)期的隨機(jī)月份數(shù)據(jù)。解決這個(gè)問題,mysql 8提供了一個(gè)方法:使用with語句。
with mo1 as (select date_format(date_add('2023-11-01', interval floor(rand() * datediff(curdate(), '2023-11-01')) day), '%y-%m') as month) select * from teacher join mo1 on mo1.month = date_format(create_time, '%y-%m')
然而,更好的解決方案是:
- 代碼生成查詢條件:在代碼中生成隨機(jī)月份,而不是使用sql語句。
- 避免使用函數(shù)索引:date_format()會(huì)阻止索引使用,導(dǎo)致查詢變慢。如果數(shù)據(jù)量大,建議外部傳入日期參數(shù)并使用between條件。
select * from teacher where create_time between '2024-01-01 00:00:00' and '2024-01-31 23:59:59'
- 創(chuàng)建索引:為create_time列創(chuàng)建索引。
alter table teacher add index (create_time);
通過這些優(yōu)化,可以有效解決mysql中的日期匹配和隨機(jī)月份問題,提高查詢性能。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END