MySQL复杂的嵌套视图值

问题描述

我将这些值放在表中

mytable

+------------------+---------------------+-----------------+
| field1           | field2              |field3           | 
+------------------+---------------------+-----------------+
| 1                | 10                  |         0       |
| 1                | 20                  |         0       |
| 2                | 100                 |         0       |
| 2                | 200                 |         0       |
| 3                |                     |         1       |
| 3                |                     |         2       |
| 4                |                     |         3       |
+------------------+---------------------+-----------------|

我想创建一个视图,让我得到这个结果

我查看所需的结果

+------------------+---------------------+-----------------+
| field1           | field2              |field3           | 
+------------------+---------------------+-----------------+
| 1                | 10                  |         0       |
| 1                | 20                  |         0       |
| 2                | 100                 |         0       |
| 2                | 200                 |         0       |
| 3                | 30                  |         1       |
| 3                | 300                 |         2       |
| 4                | 330                 |         3       |
+------------------+---------------------+-----------------|
30  is the sum of field2 where field1=1 (value of field3)
300 is the sum of field2 where field1=2 (value of field3)
330 is the sum of field2 where field1=3 (value of field3)

我如何获得30,300和330的值?

解决方法

对于MySQL 8+,使用

WITH RECURSIVE
cte AS ( SELECT field1,field2,field3
         FROM mytable
         WHERE field2 IS NOT NULL
       UNION ALL
         SELECT mytable.field1,cte.field2,mytable.field3
         FROM cte
         JOIN mytable ON cte.field1 = mytable.field3 )
SELECT field1,SUM(field2) field2,field3
FROM cte
GROUP BY field1,field3,CASE WHEN field3 = 0 THEN RAND() ELSE field3 END;

fiddle