2011-06-14 106 views
1

我想在我的MySQL表中找到特定的时间段。有条件where子句mysql

我想找到的时期,
1.开始,在过去(cursusperiode_van < now()
2.将持续至少4周(cursusperiode_tot - INTERVAL 28 DAY > now()
3.如果我不觉得这是一个,我想找到这个之后第一个开始的那个(cursusperiode_van > now() order by cursusperiode_van asc limit 1)。

期间不重叠,至少不超过1天。

比方说,我有

id:1 - period: 1 jan 2011 to 1 aug 2011 
id:2 - period: 1 aug 2011 to 31 dec 2011 

如果我查询该数据库在7月1日,我想找到id 1,如果我查询7月23日,我想找到id 2

不太可能是相关的,但此查询将被嵌入到另一个查询像

select * from cursus where cursus_periode_id in (
    select cursusperiode_id from cursusperiode_id where ...[panic!] ... 
) and so on 

我试图用IFNULL,CASE,但我似乎无法让我的头周围。我如何将这两个贴在一起?
任何暗示或帮助表示赞赏。谢谢。

回答

0

您可以在UNION这两个查询中添加一个虚拟列来帮助排序并保留找到的第一个。

SQL语句

SELECT c1.* 
FROM cursus c1 
     INNER JOIN (
      SELECT 1 AS Dummy 
        , cursusperiode_id 
      FROM cursusperiode_id 
      WHERE cursusperiode_tot - INTERVAL 28 DAY > now() 
      UNION ALL  
      SELECT 2 AS Dummy 
        , cursusperiode_id 
      FROM cursusperiode_id 
      WHERE cursusperiode_van > now()  
     ) c2 ON c2.cursusperiod_id = c1.cursusperiod_id 
ORDER BY 
     c2.Dummy 
     , c1.cursusperiode_van ASC 
LIMIT 1    
+0

谢谢您的answe。事情,我需要的查询将作为现有查询中的子查询。实际上,使用IN('select * from table where id_field IN(subquery)')和你的解决方案有2列作为输出的子查询,所以它不能做到这一点。我尝试过以另一种方式使用'UNION ALL',但我仍然无法正确使用,因为我需要使用Dummy列来排序结果。 – 2011-06-16 07:36:14

+0

在旁注中,我的服务器上的MySQL版本不能将ALL/IN和LIMIT一起使用,所以我在后面添加了select * from('subquery和')alias'。 – 2011-06-16 07:39:26

+0

而不是使用'IN',你可以''JOIN'这个查询的结果与你的表。 – 2011-06-16 09:44:22