返回给定周的所有记录

时间:2013-01-16 19:54:30

标签: php mysql

我希望返回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

*** TEST SCRIPT ** *

//$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>');

2 个答案:

答案 0 :(得分:1)

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

WHERE dateColumn > STR_TO_DATE('1,5,2012', '%w,%v,%Y') 
               AND dateColumn < STR_TO_DATE('0,5,2012', '%w,%v,%Y')

答案 1 :(得分:0)

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

SELECT * FROM Table1 WHERE T.Date1 BETWEEN '01-29-2012 00:00:00' AND '02-04-2012 00:00:00'