0

我有这两张表:

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(忽略该项目的较小日期/日期范围)并检查当前日期是否在该范围内,就像在下一个表中一样(假设今天的 02 2013 年 1 月):

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

我试图通过下一个查询获取第三张表:

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

4 回答 4

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
于 2013-01-02T20:14:20.617 回答
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);
于 2013-01-02T19:54:07.840 回答
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 ;
于 2013-01-02T20:17:44.840 回答
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
于 2013-01-02T20:04:35.337 回答