MySQL选择,加入,比较日期失败

时间:2013-01-02 19:49:47

标签: mysql

我有这两个表:

DateRanges

some_id   start_date    end_date
---------------------------------
1         2012-12-01   2012-12-15
1         2013-01-01   2013-01-15
3         2013-01-03   2013-01-10


Items

id      name
----------------
1     Some name
2     Other name
3     So on...

我尝试实现的是为Items表中的每个元素获取最大start_date(忽略该项的较小日期/日期范围)并检查当前日期是否在这个范围,如下表所示(假设今天是2013年1月2日):

id       name          TodayIsInTheRange
---------------------------------------------
1      Some name             true
2      Other name            false
3      So on...              false

我尝试使用下一个查询获取第3个表:

SELECT A.*, (B.`start_date` <= CURRENT_DATE AND CURRENT_DATE <= B.`end_date`) AS `TodayIsInTheRange`                                            
FROM `Items` as A                                                
LEFT JOIN `DateRanges` as B ON                                            
A.id = B.some_id
SORT BY B.`end_date` DESC

但是对于这个查询,我的项目会重复,因为我在同一项目的DateRanges中有两条记录。

4 个答案:

答案 0 :(得分:2)

我使用SQL Server,但我觉得这样的事情应该非常接近:

SELECT 
    I.Id, 
    I.Name,
    (DR.start_date <= CURRENT_DATE AND CURRENT_DATE <= DR.end_date) AS `TodayIsInTheRange`
FROM `Items` AS I
    LEFT JOIN 
        (SELECT Some_Id, MAX(Start_Date) as MaxStartDate 
        FROM `DateRanges`
        GROUP BY Some_ID) AS HDR ON I.Id = HDR.Some_Id
    LEFT JOIN `DateRanges` AS DR ON HDR.Some_Id = DR.Some_Id AND HDR.MaxStartDate = DR.Start_Date

答案 1 :(得分:1)

select * from items join date_ranges dr0 on items.id = dr0.some_id
  where start_date = 
       (select max(start_date) from date_ranges dr1 where dr0.some_id = dr1.some_id);

答案 2 :(得分:1)

SELECT 
  a.*, 
  ( b.start_date <= CURRENT_DATE 
  AND CURRENT_DATE <= b.end_date ) AS TodayIsInTheRange 
FROM 
    Items AS a 
  LEFT JOIN 
    ( SELECT some_id, MAX(start_date) AS start_date
      FROM DateRanges
      GROUP BY some_id
    ) AS m
    JOIN 
      DateRanges AS b 
        ON b.some_id = m.some_id
      ON a.id = m.some_id
ORDER BY b.end_date DESC ;

答案 3 :(得分:0)

尝试使用GROUP BYMAX功能。第一行为每个item.id提供一行,第二行告诉您是否在您的范围内至少有一个日期

SELECT A.*, MAX(B.`start_date` <= CURRENT_DATE AND CURRENT_DATE <= B.`end_date`) AS `TodayIsInTheRange`                                            
FROM `Items` as A                                                
LEFT JOIN `DateRanges` as B ON                                            
A.id = B.some_id
GROUP BY A.id
ORDER BY B.`end_date` DESC