Keith
Keith

Reputation: 26499

MySQL date comparison filter

I have some SQL code that works great and returns the desired results from my Wordpress database.

However, I simply cannot get my head around how to filter dates between say:

2010-12-10 00:00:00

and

2010-12-15 00:00:00

Here is my SQL code:

$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 ";

Upvotes: 3

Views: 5996

Answers (2)

Brad Christie
Brad Christie

Reputation: 101614

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

Like so?

EDIT: forgot a closing quote. oops

EDITv2: Adding your code with the updated query

EDITv3: little optimization removed 1=1 comparison, uses IN() for 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

Upvotes: 6

Pradeep Singh
Pradeep Singh

Reputation: 3634

use between date1 and date2

Upvotes: 1

Related Questions