0

以下是日期的格式:

 XXXXXX001221

这个日期是 12 月 21 日

如果我想使用 CURDATE() 函数获取昨天的条目,我该怎么做?

4

2 回答 2

1

如果你只是在做月-日(索引基于 CURDATE() 的字符串格式,即 YYYY-MM-DD):

SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 6 FOR 2),
              SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 9 FOR 2));

或者使用 EXTRACT() 的另一种方法:

SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
              EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));




也适用于年份:

SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 3 FOR 2),
              SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 6 FOR 2),
              SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 9 FOR 2));


SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', EXTRACT(YEAR FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
              EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
              EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));




编辑:而不是WHERE date_field LIKE ...你可以使用WHERE RIGHT(date_field, 6) = ...codethis'回答中提到的那样:

SELECT * FROM table_name
WHERE RIGHT(date_field, 4) =
  CONCAT(EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
         EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));

SELECT * FROM table_name
WHERE RIGHT(date_field, 6) =
  CONCAT(EXTRACT(YEAR FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
         EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
         EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));

注意:您也可以使用变量来保存计算 DATE_SUB(CURDATE(), INTERVAL 1 DAY) 的所有时间。

SET @yesterday = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
SELECT ...
于 2010-12-22T00:52:48.483 回答
0

尝试类似:

SELECT * FROM table WHERE RIGHT(date_col, 6) = (SELECT CONVERT(VARCHAR(6), GETDATE()-1, 12) AS [YYMMDD])
于 2010-12-22T00:53:05.390 回答