0

我希望返回 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>');
4

2 回答 2

1

使用STR_TO_DATE您可以创建一周的第一天和最后一天。然后使用BETWEENor 日期算术来查找日期:

WHERE dateColumn > STR_TO_DATE('1,5,2012', '%w,%v,%Y') 
               AND dateColumn < STR_TO_DATE('0,5,2012', '%w,%v,%Y')
于 2013-01-16T19:57:08.570 回答
0

您可以计算出第五周的开始日期和结束日期,并根据 BETWEEN 运算符进行过滤

SELECT * FROM Table1 WHERE T.Date1 BETWEEN '01-29-2012 00:00:00' AND '02-04-2012 00:00:00'
于 2013-01-16T19:57:46.680 回答