我希望返回 2012 年第 5 周的所有记录。例如,以下查询将提供正确的记录,但是效率非常低,因为必须为每一行计算 WEEK() 和 YEAR() 并且索引不能用过的。我希望应该使用 BETWEEN,但我不确定我会怎么做。我还需要为给定的月份和季度做类似的事情,理想情况下可以使用类似的解决方案。如果需要,我可以用 PHP 补充 SQL。谢谢
SELECT * FROM myTable WHERE WEEK(dateColumn)=5 AND YEAR(dateColumn)=2012;
编辑 - 以下已添加到补充评论中
***测试数据** *
SELECT * FROM projects_sell WHERE award_date BETWEEN '2012-04-01' AND '2012-04-08'
0.55236601829529
SELECT * FROM projects_sell WHERE YEAR(award_date)=2012 AND WEEK(award_date)=5
0.52925586700439
SELECT * FROM projects_sell WHERE award_date > STR_TO_DATE('1,5,2012', '%w,%v,%Y') AND award_date < STR_TO_DATE('0,5,2012', '%w,%v,%Y')
0.69798302650452
***测试脚本** *
//$sql ="SELECT * FROM projects_sell WHERE award_date BETWEEN '2012-04-01' AND '2012-04-08'";
//$sql ="SELECT * FROM projects_sell WHERE YEAR(award_date)=2012 AND WEEK(award_date)=5";
$sql ="SELECT * FROM projects_sell WHERE award_date > STR_TO_DATE('1,5,2012', '%w,%v,%Y') AND award_date < STR_TO_DATE('0,5,2012', '%w,%v,%Y')";
$current_time=microtime(true);
for ($i=1; $i<=1000; $i++)
{
$stmt = db::db()->query($sql);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo($sql.'<br>'.(microtime(true)-$current_time).'<br>');