在 MySql 中将 VARCHAR 转换为 DECIMAL 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22278733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting VARCHAR to DECIMAL values in MySql
提问by Darth Coder
I have imported a CSV file that contains string values (eg.eating) and floating values (eg. 0.87) into a table in my phpMyAdmin database. After I get ride of all the string values and retain only the rows that have the decimal values, I need to convert such values from VARCHAR to DECIMAL/FLOAT so that I can perform a MAX() on this attribute.
我已将包含字符串值(例如,吃)和浮动值(例如 0.87)的 CSV 文件导入到我的 phpMyAdmin 数据库中的表中。在我处理完所有字符串值并仅保留具有十进制值的行后,我需要将这些值从 VARCHAR 转换为 DECIMAL/FLOAT,以便我可以对该属性执行 MAX()。
How do I do this? Each time I try doing this through the GUI in phpMyAdmin, all my values are automatically rounded off to 0 and 1s.
我该怎么做呢?每次我尝试通过 phpMyAdmin 中的 GUI 执行此操作时,我的所有值都会自动四舍五入为 0 和 1。
Please help me!
请帮我!
采纳答案by Sky
I think you need to try doing something like this on your MySQL if you have admin privilege on your MySQL.
如果您对 MySQL 具有管理员权限,我认为您需要尝试在 MySQL 上执行此类操作。
ALTER TABLE tablename MODIFY columnname DECIMAL(M,D)
ALTER TABLE 表名修改列名 DECIMAL(M,D)
for the M,D variables, read this - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html
对于 M、D 变量,请阅读此内容 - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html
And MySQL should be able to automatically converting a text to a numeric. Just that the data type in MySQL might not be a decimal yet that's why you can't store any decimal.
并且 MySQL 应该能够自动将文本转换为数字。只是 MySQL 中的数据类型可能不是小数,这就是您不能存储任何小数的原因。
回答by Jay Patel
Without Converting you can find Maximum using this query
无需转换,您可以使用此查询找到最大值
select max(cast(stuff as decimal(5,2))) as mySum from test;
check this SQLfiddle
检查这个SQLfiddle
your demo table:
您的演示表:
create table test (
name varchar(15),
stuff varchar(10)
);
insert into test (name, stuff) values ('one','32.43');
insert into test (name, stuff) values ('two','43.33');
insert into test (name, stuff) values ('three','23.22');
Your Query:
您的查询:
For SQL Server, you can use:
对于 SQL Server,您可以使用:
select max(cast(stuff as decimal(5,2))) as mySum from test;
回答by Alex W
Be aware that if you convert from VARCHAR
to DECIMAL
and do not specify a precicision and maximum number of digits (i.e. DECIMAL
instead of DECIMAL(5,2)
) MySQL will automatically round your decimals to integer values.
请注意,如果您从VARCHAR
to转换DECIMAL
并且不指定精度和最大位数(即DECIMAL
代替DECIMAL(5,2)
),MySQL 将自动将您的小数四舍五入为整数值。