将mysql字段值从varchar转换为int并在查询中进行比较

时间:2013-12-04 13:55:56

标签: mysql type-conversion field

我在数据库中有一个varchar字段,存储年份格式如:2004,2005,2006等...如何将varchar格式转换为int并将条件放在where子句中,以便我可以获取例如仅比2005年大几年?

我试过这个

$sql = "select t1.* from table1 t1 left join table2 t2 on t1._id = t2.id where t2.version='year' and t1.field='name' and COVERT(t1.value, UNSIGNED) > 2005";

但它没有用。感谢。

2 个答案:

答案 0 :(得分:2)

使用cast()

select t1.*
from table1 t1
left join table2 t2 on t1._id = t2.id
where t2.version='year'
and t1.field='name'
and CAST(t1.value AS UNSIGNED) > 2005

此外,您的查询中有ep.value - 我猜您的意思是t1

答案 1 :(得分:0)

Mysql可以将字符串与数字进行比较

SELECT "2006" > 2005 -- answer is true

您不需要转换功能。 也许您需要提供更多信息?