检查日期MySQL,php之间的表格类型

时间:2016-01-18 12:42:00

标签: php mysql

我有桌子如下所示:

ID, Date, Type 
1,  2015-1-1,  2 
2,  2015-5-1,  5 
3,  2015-8-10,  4


(before 2015-1-1 .... type = default  
2015-1-1 <= Date < 2015-5-1 .... type = 2  
2015-5-1 <= Date < 2015-8-10 .... type = 5  
since 2015-8-10 .... type = 4) 

我想简单检查一下$date的哪种类型。

我试过:

$sql = "SELECT * FROM smlouvy  
        WHERE Date < '".$date."'  
        ORDER BY Date LIMIT 1";

$result = MySQL_Query($sql);  
if ( mysql_num_rows($result) == 0 ) {
    $type = 'default';
}
else {
$row = mysql_fetch_array($result);
$type = $row["Type"];
}

2 个答案:

答案 0 :(得分:0)

您可以尝试以下内容:

select ID,date, 
          case  `date`
          when `date`<='2015-11-01' then 4
          when `date`>='2015-11-01' then 5
          else 1 end as `type` 
 from tbl;

注意:这只是一个示例,您可能需要根据您的要求修改条件。

答案 1 :(得分:0)

以下是解决方案(如果Date列在特定范围内匹配):

$dateFrom = '2015-5-1';
$dateTo = '2015-8-10';

// exemplary query
$query = "SELECT type FROM table_name
          WHERE $dateFrom <= Date < $dateTo 
          ORDER BY Date ASC LIMIT 1 ";
// it will return the type of lower date column from range (type = 5)