MYSQL本周选择索引

时间:2013-04-18 00:25:03

标签: mysql

用户可以看到他们本周上传的内容。我在下面有代码:

这是正确的吗?

SELECT * 
FROM images 
WHERE userid = '$userid'
   AND uploadeddate >= CURDATE() - INTERVAL WEEKDAY(day) DAY 
   AND uploadeddate < CURDATE() - INTERVAL WEEKDAY(day) DAY + INTERVAL 7 DAY 
ORDER BY uploadeddate DESC

我为(userid,uploadeddate)创建了索引。

1 个答案:

答案 0 :(得分:0)

原始查询工作day需要在您查询的数据库中(或设置为变量),它需要在MySQL日期'0000-00-00'或日期时间'0000-00-00 00:00:00'格式。

输入日期

WEEKDAY()返回0-6。

$first; //is earliest offset in the range
$last; //is the latest offset in the range

SELECT * FROM images WHERE userid = '$userid'
AND uploadeddate > CURDATE() - INTERVAL $first DAY
AND uploadeddate < CURDATE() - INTERVAL $last DAY
ORDER BY uploadeddate DESC

所以像这样的查询会返回上周的结果。

SELECT * FROM images WHERE userid = '$userid' AND
uploadeddate > CURDATE() - INTERVAL 14 DAY
AND uploadeddate < CURDATE() - INTERVAL 7 DAY
ORDER BY uploadeddate DESC