我有下表:
+------------------+
| ColumnName |
+------------------+
| 1 Slap |
+------------------+
| 13 Slap |
+------------------+
| 2 Slap |
+------------------+
只有MySQL如何解析ColumnName只能获取数值并将它们全部添加?
如果在上表中执行此操作,查询的输出应为16。
答案 0 :(得分:6)
SELECT SUM(CAST(ColumnName as SIGNED)) FROM TableName
(如果您没有任何负数,则为UNSIGNED
)
编辑:测试数据以满足怀疑论者。
mysql> select * from testtable;
+---------+
| testcol |
+---------+
| 1 Slap |
| 13 Slap |
| 2 Slap |
+---------+
3 rows in set (0.00 sec)
mysql> select sum(cast(testcol as unsigned)) from testtable;
+--------------------------------+
| sum(cast(testcol as unsigned)) |
+--------------------------------+
| 16 |
+--------------------------------+
1 row in set, 3 warnings (0.00 sec)
mysql>
答案 1 :(得分:1)
SELECT SUM(CAST(LEFT(ColumnName, INSTR(ColumnName, ' ')) as SIGNED))
FROM Table