为什么数学运算符与sql中的字符串交互

时间:2016-04-07 10:06:25

标签: mysql operators

假设我使用sql查询:

select * from table t where t.name = "adam" and t.age > 10;

并且在" age"列中,不仅仅是整数值。还有价值观" old"," young"等...

此查询的结果将是年龄超过10岁的所有亚当,但也包含年龄等于其中一个字符串值的所有亚当" old", "年轻"等...

为什么会这样?

1 个答案:

答案 0 :(得分:1)

The reason for this behavior is MySQLs Type Conversion which occurs implicit when you apply operators to data/columns of different types.

To the example you posted: It's generally considered bad practice to save data of different types/meanings in the same field.

I'd set the type of your 'age' column to 'int', and make it nullable. Then add another column named about_age which could be an ENUM with the values old and young. Whenever the 'age' column is NULL, your application can check the the about_age column. Only with this way, it's completely clear what your data means.