简体   繁体   English

在MySQL中将文本列转换为整数

[英]Converting text column to integer in MySQL

I'm trying to create a cleaned-up table that replaces a varchar(50) field with an integer. 我正在尝试创建一个清理表,以整数替换varchar(50)字段。 The original field has occasional text values that I'd like to convert to 0 or null values. 原始字段偶尔会有文本值,我想将其转换为0或null值。 I can do this in a select statement just fine, but get an error when trying to create my table. 我可以在select语句中做到这一点,但是在尝试创建表时出现错误。

Below is a minimal example that uses strings: 以下是使用字符串的最小示例:

/* This works */
DROP TABLE IF EXISTS mytest;
CREATE TABLE mytest
AS
   SELECT convert("123", unsigned) AS mynum;

/* This works, returning a row of 0 */
SELECT convert("TEST", unsigned) AS mynum;

/* But this fails, with:  Truncated incorrect INTEGER value: 'TEST'*/
DROP TABLE IF EXISTS mytest;
CREATE TABLE mytest
AS
   SELECT convert("TEST", unsigned) AS mynum;`

What is wrong with the above, and is there a better way to accomplish what I want? 上面有什么问题,有没有更好的方法来实现我想要的? Thanks for the help. 谢谢您的帮助。

I don't have an explanation for why that error occurs, but I found a workaround using a subquery: 我没有解释为什么会发生该错误的原因,但是我发现了使用子查询的解决方法:

DROP TABLE IF EXISTS mytest;
CREATE TABLE mytest
AS
    SELECT mynum
    FROM (SELECT convert("TEST"), unsigned) AS mynum) t;

Demo: http://www.sqlfiddle.com/#!2/4909a/1 演示: http ://www.sqlfiddle.com/#!2/ 4909a/1

I'd use a case statement for it and also switch over to using CAST instead of convert so you'll get failures instead of implicit conversions. 我将为此使用case语句,并切换到使用CAST而不是convert,这样您将获得失败而不是隐式转换。

CREATE TABLE mytest(myVarchar varchar(10));
INSERT mytest VALUES ('123'),('TEST');

SELECT CASE
    WHEN  myVarchar REGEXP '^[0-9]+$' THEN CAST(myVarchar,unsigned)
    ELSE 0
END As mynum
FROM mytest;

I don't have a mysql instance handy to test this so hopefully I didn't goof any syntax errors. 我没有方便地测试该实例的mysql实例,因此希望我不会遇到任何语法错误。

Rather than convert, you could update the data and then alter the table: 除了转换,您可以更新数据,然后更改表:

UPDATE mytest SET mynum=mynum + 0;
ALTER TABLE mytest CHANGE COLUMN mynum mynum INT UNSIGNED;

It looks like you are implicitly defining the column name by the select statement in the create. 看起来您正在通过create中的select语句隐式定义列名称。 This may be assuming the "TEST" string is the datatype. 这可能是假设“ TEST”字符串是数据类型。 It would help to see the error message you get, but my assumption would be to explicitly define the column as: 这将有助于查看您收到的错误消息,但是我的假设是将列明确定义为:

CREATE TABLE mytest(mynum int);

Then 然后

Insert into mytest(mynum)
select convert("TEST",unsigned) as mynum;

This is also why the answer with the subquery may work, by the time it gets to the outer query it is implicitly defined as an int. 这也是为什么子查询的答案可以起作用的原因,因为当它到达外部查询时,它被隐式定义为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM