使用with解决mysql日期匹配及随机月份问题
原始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')
然而,更好的解决方案是:
select * from teacher where create_time between '2024-01-01 00:00:00' and '2024-01-31 23:59:59'
alter table teacher add index (create_time);
通过这些优化,可以有效解决mysql中的日期匹配和随机月份问题,提高查询性能。