MySQL从上周选择数据

时间:2014-01-09 08:08:32

标签: mysql

我想知道如何选择上周的所有数据?星期一到星期五,假设今天是星期一。我实际上没有日期时间格式列。

这是我到目前为止所尝试的内容:

SELECT * FROM logs
WHERE WEEKDAY(CONCAT(year,'-',month,'-',day)) BETWEEN 0 AND 4 
AND YEARWEEK( date_added2 ) = YEARWEEK( CURRENT_DATE( ) - INTERVAL 7 DAY) AND deleted='n';

这是我的桌子,桌面日志:

enter image description here

1 个答案:

答案 0 :(得分:0)

你可以尝试一下吗?你可以在这里测试http://www.sqlfiddle.com/#!2/3989b1/3/0

SELECT *
FROM logs,
  (SELECT (CURRENT_DATE() - INTERVAL (WEEKDAY(CURRENT_DATE()) + 1 ) % 7 DAY) AS sun_day) t1
WHERE
    logs.date_added2 BETWEEN t1.sun_day - INTERVAL 6 DAY 
        AND t1.sun_day - INTERVAL 2 DAY;

工作原理

folling查询返回星期日

SELECT '2014-01-09' - INTERVAL (WEEKDAY('2014-01-09') + 1 ) % 7 DAY;
+--------------------------------------------------------------+
| '2014-01-09' - INTERVAL (WEEKDAY('2014-01-09') + 1 ) % 7 DAY |
+--------------------------------------------------------------+
| 2014-01-05                                                   |
+--------------------------------------------------------------+

SELECT '2014-01-10' - INTERVAL (WEEKDAY('2014-01-10') + 1 ) % 7 DAY;
+--------------------------------------------------------------+
| '2014-01-10' - INTERVAL (WEEKDAY('2014-01-10') + 1 ) % 7 DAY |
+--------------------------------------------------------------+
| 2014-01-05                                                   |
+--------------------------------------------------------------+

所以,t1.sun_day - INTERVAL 6在上周的星期一举行,t1.sun_day - INTERVAL 2 DAY在上周五举行。

mysql> SELECT @sunday := (CURRENT_DATE() - INTERVAL (WEEKDAY(CURRENT_DATE()) + 1 ) % 7 DAY) AS sunday;
+------------+
| sunday     |
+------------+
| 2014-01-05 |
+------------+

mysql> SELECT @sunday - INTERVAL 6 DAY, @sunday -  INTERVAL 2 DAY;
+--------------------------+---------------------------+
| @sunday - INTERVAL 6 DAY | @sunday -  INTERVAL 2 DAY |
+--------------------------+---------------------------+
| 2013-12-30               | 2014-01-03                |
+--------------------------+---------------------------+

因此,logs.date_added2 BETWEEN t1.sun_day - INTERVAL 6 DAY AND t1.sun_day - INTERVAL 2 DAY会在星期一到星期五找到日志。