0

我有一个包含以下字段的表:

State_Code    School_Code    Established_Year    Data_Year
    12        12016837383          1962           2011-12
    12        12018383799          1996           2011-12
    12        12024895748          2007           2011-12
    12        12037849837          1987           2011-12

在这里,所有这些字段都是 VARCHAR 类型的。

我想检索 1990 年之前建立的所有学校。我触发了这个查询:

Select 
  School_Code, 
  date_format(str_to_date(Established_Year,'%y'),'%y') as Year,   
  date_format(str_to_date(Data_Year,'%y'),'%y') as Data_Year 
from 
  Table1 
WHERE 
  Established_Year < 1990;

但它返回这个:

School_Code    Year    Data_Year
12016837383     19      20
12037849837     19      20

我也尝试使用CONVERT函数,如:

Select 
  School_Code, 
  Convert(Established_Year, YEAR) as Year 
from 
  Table1 
WHERE 
  Established_Year < 1990;

但它抛出了这个错误:

Error Code: 1064
You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax 
to use near 'YEAR' at line 1
4

1 回答 1

1

您实际上可以将其转换为 int。

SELECT * 
FROM   TableName
WHERE  CAST(Established_Year AS UNSIGNED) < 1990

更新 1

根据您的评论,如果您要检索 Data_Year 在 2010-11 之前的 School_Codes,您需要将其转换Data_Year为实际日期。

SELECT School_Code    
FROM   TableName
WHERE  STR_TO_DATE(CONCAT(Data_Year, '-01'), '%Y-%m-%d') < DATE('2010-11-01')
于 2013-04-13T07:13:31.353 回答