如何替换最后一个字符?

时间:2015-11-20 13:18:49

标签: mysql replace

这是我的表:

// table
+----+--------+
| id | number |
+----+--------+
| 1  | 123    |
| 2  | 123.   |
| 3  | 12.3   |
+----+--------+

我想要这个:

// newtable
+----+--------+
| id | number |
+----+--------+
| 1  | 123    |
| 2  | 123    |
| 3  | 12.3   |
+----+--------+

我该怎么做?

我可以这样做:(但我正在寻找更快更好的方法)

// Not tested, But I think this works!
SELECT 
  id, 
  IF(RIGHT(number,1) == '.', REPLACE(number, '.', ''), number)
FROM table
// also I can use CAST(number as unsigned) instead of REPLACE(number, '.', '')

那么,还有更好的解决方案吗? (没有IF - 陈述)

3 个答案:

答案 0 :(得分:3)

SELECT id, CONVERT(number, DECIMAL(10,6)) FROM test

答案 1 :(得分:2)

如果要更改表格中的数据,请使用此

mysql> CREATE TABLE test(
    -> id INT(1),
    -> number VARCHAR(5)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO test
    -> VALUES(1, '123'),
    -> (2, '123.'),
    -> (3, '12.3');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM test;
+------+--------+
| id   | number |
+------+--------+
|    1 | 123    |
|    2 | 123.   |
|    3 | 12.3   |
+------+--------+
3 rows in set (0.00 sec)

mysql> UPDATE test
    -> SET number=REPLACE(number, '.', '')
    -> WHERE RIGHT(number,1) = '.';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM test;
+------+--------+
| id   | number |
+------+--------+
|    1 | 123    |
|    2 | 123    |
|    3 | 12.3   |
+------+--------+
3 rows in set (0.00 sec)

如果您只想获取此表单中的数据

,请使用此选项
mysql> DROP TABLE IF EXISTS test;
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE test(
    ->   id INT(1),
    ->   number VARCHAR(5)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO test VALUES
    ->   (1, '123'),
    ->   (2, '123.'),
    ->   (3, '12.3')
    -> ;
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM test;
+------+--------+
| id   | number |
+------+--------+
|    1 | 123    |
|    2 | 123.   |
|    3 | 12.3   |
+------+--------+
3 rows in set (0.00 sec)

mysql> SELECT
    ->   id,
    ->   CASE
    ->     WHEN RIGHT(number,1) = '.' THEN floor(number)
    ->     ELSE number
    ->   END AS number
    -> from test;
+------+--------+
| id   | number |
+------+--------+
|    1 | 123    |
|    2 | 123    |
|    3 | 12.3   |
+------+--------+
3 rows in set (0.00 sec)

答案 2 :(得分:2)

删除最后相应的字符(如果存在)

A -> B