使用with解決mysql日期匹配及隨機(jī)月份問(wèn)題
原始sql遇到詭異情況,查詢不到預(yù)期的隨機(jī)月份數(shù)據(jù)。解決這個(gè)問(wèn)題,mysql 8提供了一個(gè)方法:使用with語(yǔ)句。
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')
登錄后復(fù)制
然而,更好的解決方案是:
- 代碼生成查詢條件:在代碼中生成隨機(jī)月份,而不是使用sql語(yǔ)句。
- 避免使用函數(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'
登錄后復(fù)制
- 創(chuàng)建索引:為create_time列創(chuàng)建索引。
alter table teacher add index (create_time);
登錄后復(fù)制