2014-05-06 91 views
0

我有一個查詢得到一個VARCHAR數據類型

SELECT * from table1 where sy='$school_year'; 

與上年我

$school_year='2013-2014'  //which is a varchar 

我怎樣才能讓

$school_year='2012-2013' 

我已經試過

SELECT * from table1 where sy='$school_year'-1; 

但給我一個錯誤,指出$ school_year不是一個整數。我怎樣才能得到以前的$ school_year?或者有可能嗎?

+0

如果您擁有數據庫設計的控制權,請考慮將此字段更改爲僅包含學期的開始或結束年份。生活變得更容易,而不僅僅是這個特定的問題。 –

+0

我同意喬納森所說的..重組你的表格會更好,並且更容易做到未來的查詢。嘗試將字符串拆分爲兩列,並在需要時將其連接。:) id,from_year,to_year 1,2013,2014 CONCAT_WS(' - ',from_year,to_year) –

回答

1

或者,你可以這樣做:看看這個例子:

$school_year='2013-2014'; 
$school_year = explode('-', $school_year); 
$school_year[0] = ((int) $school_year[0] - 1); 
$school_year[1] = ((int) $school_year[1] - 1); 
$school_year = implode('-', $school_year); 

$statement = "SELECT * from table1 where sy='$school_year';"; 
echo $statement; 

// Sample 
// SELECT * from table1 where sy='2012-2013'; 
0

這是一個方式來獲得前次值:

select * 
from table1 
where sy < '$school_year' 
order by sy desc 
limit 1; 
0
$year = '2013-2014'; 

$prev_year = substr($year, 0, 4); 
$prev_year = ($prev_year-1) . '-' . $prev_year; 

$q = "SELECT * FROM table1 WHERE sy='$prev_year'"; 

$q

SELECT * FROM table1 WHERE sy='2012-2013' 
相關問題