Mysql比较属于同一ID的两行中的值

时间:2014-10-02 12:54:10

标签: php mysql

我有以下mysql表,并且只想检索那些当前日位于post_id meta_valuestart_date之间的end_date(格式为mmdd)。截至今天(10月10日),只返回post_id 11。 如何对属于同一post_id的两行(开始日期和结束日期)进行比较

请帮帮我!

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

3 个答案:

答案 0 :(得分:2)

在查询中使用JOIN

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

为什么JOIN - 因为我们需要比较表格中两个不同行的值(一个meta_key = 'start_date'和另一个meta_key = 'end_date')。

答案 1 :(得分:0)

如果我理解你的要求(用实际数据会更容易),这是相当简单的 -

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

答案 2 :(得分:0)

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