关于sql:从VARCHAR转换为INT – MySQL

Cast from VARCHAR to INT - MySQL

我目前的数据

1
SELECT PROD_CODE FROM `PRODUCT`

1
2
3
4
5
6
7
8
9
PROD_CODE
2
5
7
8
22
10
9
11

我已经尝试了所有四个查询,但都没有工作。(参考文献)

1
2
3
4
5
6
7
SELECT CAST(PROD_CODE) AS INT FROM PRODUCT;

SELECT CAST(PROD_CODE AS INT) FROM PRODUCT;

SELECT CAST(PROD_CODE) AS INTEGER FROM PRODUCT;

SELECT CAST(PROD_CODE AS INTEGER) FROM PRODUCT;

所有抛出语法错误,如下所示:

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 ') AS INT FROM PRODUCT LIMIT 0, 30' at line 1

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 'INTEGER) FROM PRODUCT LIMIT 0, 30' at line 1

在MySQL中将varchar强制转换为整数的正确语法是什么?

MySQL版本:5.5.16


如Cast Cast和Operators中所述:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

因此,您应该使用:

1
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT


对于将varchar字段/值转换为数字格式,可以使用少量hack:

1
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`