0

This is what I have tried, but did not work.

SELECT COUNT(*) AS month_count
FROM `wp_postmeta`
WHERE
     `meta_key`='from_dt' AND
      (`meta_value` BETWEEN '$st' AND '$end') AND
      (`meta_value` BETWEEN '$st1' AND '$end1');

I'm trying to count the number of months which come between epoch time of $st and $end of this year & between $st1 and $end1 of next year. Say I have 2 dates (feb 2013 and feb 2014)in meta_value fields, I want the query to return 2(as there are 2 February's).

How to use 2 between operators in one sql statement?

2
  • 3
    The meta_value cannot be two different values at the same time, do you mean OR? Commented May 2, 2013 at 14:03
  • Actually i'm trying to count the number of months which come between epoch time of $st and $end of this year & $st1 and $end1 of next year. Commented May 2, 2013 at 14:07

5 Answers 5

2

Nothing technically wrong with your query, but depending on your desired results, you probably want to be using OR -- just make sure your parentheses are in the correct place:

SELECT COUNT(*) AS month_count
FROM `wp_postmeta`
WHERE
     `meta_key`='from_dt' AND
      ((`meta_value` BETWEEN '$st' AND '$end') OR
      (`meta_value` BETWEEN '$st1' AND '$end1'))

Your current query is requiring the meta_value be between both sets of numbers which may be your problem.

Sign up to request clarification or add additional context in comments.

Comments

0

do you mean this?

SELECT COUNT(*) AS month_count
FROM `wp_postmeta`
WHERE
      (`meta_key`='from_dt' AND `meta_value` BETWEEN '$st' AND '$end') OR
      (`meta_key`='from_dt' AND `meta_value` BETWEEN '$st1' AND '$end1')

Comments

0

Perhaps you are looking for two different rows that are in these ranges. For that, use a having clause:

SELECT COUNT(*) AS month_count
FROM `wp_postmeta`
WHERE `meta_key`='from_dt'
having sum(case when `meta_value` BETWEEN '$st' AND '$end' then 1 else 0 end) > 0 AND
       sum(case when `meta_value` BETWEEN '$st1' AND '$end1' then 1 else 0 end) > 0);

Comments

0
SELECT COUNT(*) AS month_count 
FROM `wp_postmeta` 
WHERE `meta_key`='from_dt' AND
(`meta_value` BETWEEN '$st' AND '$end') OR (`meta_value` BETWEEN '$st1' AND '$end1');

Comments

0

I think that you want an OR there instead of an AND. Think that in an AND bith conditions must be satisfied whereas in an OR one condition is enough.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.