原始sql遇到詭異情況,查詢不到預期的隨機月份數據。解決這個問題,mysql 8提供了一個方法:使用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')
登錄后復制
然而,更好的解決方案是:
- 代碼生成查詢條件:在代碼中生成隨機月份,而不是使用sql語句。
- 避免使用函數索引:date_format()會阻止索引使用,導致查詢變慢。如果數據量大,建議外部傳入日期參數并使用between條件。
select * from teacher where create_time between '2024-01-01 00:00:00' and '2024-01-31 23:59:59'
登錄后復制
- 創建索引:為create_time列創建索引。
alter table teacher add index (create_time);
登錄后復制