mysql表:
table_results
:
id results
1 1 0 1 2 4 5
2 5 4 2 6
3 7 2 8 2 4
我正在创建一个我需要的Yii gridview
SELECT SUM(results) AS results2 FROM table_results WHERE id = 1:
例如我必须对第一行求和:1 + 0 + 1 + 2 + 4 + 5并且作为results2 = 15。
如何在sql中做到这一点?
答案 0 :(得分:2)
不需要动态SQL。您可以使用:
<强> SqlFiddleDemo 强>
SELECT sub.id, SUM(sub.val) AS `sum`
FROM
(
SELECT id, SUBSTRING_INDEX(SUBSTRING_INDEX(t.results, ' ', n.n), ' ', -1) AS val
FROM table_results t
CROSS JOIN
(
SELECT a.N + b.N * 10 + 1 n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
) n
WHERE n.n <= 1 + (LENGTH(t.results) - LENGTH(REPLACE(t.results, ' ', '')))
) sub
-- WHERE sub.id = 1
GROUP BY sub.id
答案 1 :(得分:1)
执行此操作的一种方法是使用动态SQL。所以,完全在MySQL中:
declare @sql varchar(2000);
select @sql = concat('select ', replace(results, ' ', '+'))
from table_results tr
where id = 1;
prepare s from @sql;
execute s;
deallocate prepare s;
作为注释:仅仅因为我回答了这个问题并不意味着我宽恕了数据结构。