user3200582
user3200582

Reputation: 43

Mysql compare values in two rows that belong to the same ID

I have the following mysql table and would like to retrieve only those post_id's where the current day lies between the meta_value of start_date and end_date (formatted as mmdd). So as of today (October 10th) only post_id 11 would be returned. How can I make this comparison of two rows (start and end date) that belong to the same post_id??

Please help me out!

╔═════════╦═══════════════╦════════════╗
║ post_id ║   meta_key    ║ meta_value ║
╠═════════╬═══════════════╬════════════╣
║ 10      ║ start_date    ║ 0101       ║
║ 10      ║ end_date      ║ 1231       ║
║ ...     ║ ...           ║ ...        ║
║ ...     ║ ...           ║ ...        ║
║ 11      ║ start_date    ║ 0101       ║
║ 11      ║ end_date      ║ 0131       ║
║ ...     ║ ...           ║ ...        ║
║ ...     ║ ...           ║ ...        ║
╚═════════╩═══════════════╩════════════╝

Upvotes: 0

Views: 77

Answers (3)

Strawberry
Strawberry

Reputation: 33945

DROP TABLE IF EXISTS eav_hell;

CREATE TABLE eav_hell
(post_id INT NOT NULL
,meta_key    VARCHAR(30) NOT NULL
,meta_value DATE NOT NULL
);

INSERT INTO eav_hell VALUES
(10      ,'start_date',20140101),
(10      ,'end_date',20141231),
(11      ,'start_date',20140101),
(11      ,'end_date',20140131);

SELECT x.post_id
     , MAX(CASE WHEN meta_key = 'start_date' THEN meta_value END) start_date
     , MAX(CASE WHEN meta_key = 'end_date' THEN meta_value END) end_date
  FROM eav_hell x
 GROUP 
    BY post_id
HAVING STR_TO_DATE('20140201','%Y%m%d') BETWEEN start_date AND end_date;

+---------+------------+------------+
| post_id | start_date | end_date   |
+---------+------------+------------+
|      10 | 2014-01-01 | 2014-12-31 |
+---------+------------+------------+

http://www.sqlfiddle.com/#!2/b38347/2

Upvotes: 0

Rimas
Rimas

Reputation: 6024

Use JOIN in query:

SELECT t1.post_id
  FROM table_name t1
  JOIN table_name t2 ON t2.post_id = t1.post_id
 WHERE t1.meta_key = 'start_date'
   AND t2.meta_key = 'end_date'
   AND DATE_FORMAT(NOW(), '%m%d') BETWEEN t1.meta_value AND t2.meta_value

Why JOIN - because we need compare values from two different rows in table (one with meta_key = 'start_date' and other meta_key = 'end_date').

Upvotes: 2

Jay Blanchard
Jay Blanchard

Reputation: 34416

It is fairly simple if I understand what you're asking (would be easier with actual data) -

SELECT `post_id`
FROM `table`
WHERE `meta_value` BETWEEN 'start_date' AND 'end_date' -- supply actual dates here

Upvotes: 0

Related Questions