简体   繁体   中英

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       ║
║ ...     ║ ...           ║ ...        ║
║ ...     ║ ...           ║ ...        ║
╚═════════╩═══════════════╩════════════╝

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' ).

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM