MySQL日期比较过滤器

时间:2010-12-10 18:52:30

标签: mysql datetime filter

我有一些效果很好的SQL代码,可以从我的Wordpress数据库中返回所需的结果。

但是,我根本无法理解如何过滤说明之间的日期:

2010-12-10 00:00:00

2010-12-15 00:00:00

这是我的SQL代码:

$SQL_K =  "SELECT SQL_CALC_FOUND_ROWS wp_posts.* 
             FROM wp_posts 
             JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
            WHERE 1 = 1 
              AND wp_posts.post_type = 'post' 
              AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') 
              AND wp_postmeta.meta_key = 'expiry_date' 
         GROUP BY wp_posts.ID 
         ORDER BY wp_posts.post_date DESC 
            LIMIT 0, 100 ";

2 个答案:

答案 0 :(得分:6)

WHERE date_column BETWEEN STR_TO_DATE('2010-12-10', '%Y-%m-%d') AND STR_TO_DATE('2010-12-15', '%Y-%m-%d')

喜欢这样吗?

编辑:忘了结束语。糟糕

EDITv2:使用更新后的查询添加代码

EDITv3:小优化 删除1 = 1比较,使用IN()表示wp_posts.post_status

SELECT      SQL_CALC_FOUND_ROWS wp_posts.* 
FROM        wp_posts 
  JOIN      wp_postmeta 
  ON        (wp_posts.ID = wp_postmeta.post_id) 
WHERE       wp_posts.post_type = 'post' 
  AND       (wp_posts.post_status IN ('publish','private'))
  AND       wp_postmeta.meta_key = 'expiry_date' 
  AND       ___INSERT_NAME_OF_DATE_COLUMN_HERE___
    BETWEEN STR_TO_DATE('2010-12-05', '%Y-%m-%d')
      AND   STR_TO_DATE('2010-12-15', '%Y-%m-%d')
GROUP BY    wp_posts.ID 
ORDER BY    wp_posts.post_date DESC 
LIMIT       0, 100

答案 1 :(得分:1)

use between date1 and date2