更改列类型并为此类型设置适当格式的值

时间:2015-08-03 11:27:56

标签: mysql sql

我有一个带有整数值的列NODE。如何更改列类型以使用以下格式进行更改:

Old column:  New Column:
NODE         NODE
1            N0C00001
127          NOC00127
13           NOC00013

2 个答案:

答案 0 :(得分:1)

您可以尝试这些。

SELECT CONCAT('N0C',LPAD('1',5,0));

语法:SELECT CONCAT('N0C', LPAD(your_column_name,5,0)) from table_name;

SQL:SELECT CONCAT('N0C', LPAD(old_columnname_NODE,5,0)) as new_columnname_NODE from table_name;

更新sql:update table_name set NODE = CONCAT('N0C', LPAD(old_columnname_NODE,5,0));

谢谢。

答案 1 :(得分:1)

在这里你可以做什么,

mysql> select concat(left('N0C0000',length('N0C0000')-length('1')),'1') as r;
+---------+
| r       |
+---------+
| N0C0001 |
+---------+
1 row in set (0.00 sec)

现在将此更改为更新命令将类似于

update table_name 
set node = concat(left('N0C0000',length('N0C0000')-length(node)),node);

这是一个测试用例

mysql> select * from test ;
+------+
| node |
+------+
| 1    |
| 127  |
| 13   |
+------+
3 rows in set (0.00 sec)

mysql> update test set node = concat(left('N0C0000',length('N0C0000')-length(node)),node);
Query OK, 3 rows affected (0.05 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select * from test ;
+---------+
| node    |
+---------+
| N0C0001 |
| N0C0127 |
| N0C0013 |
+---------+
3 rows in set (0.00 sec)