我有如下表格
Id UserName PercentSharing ParentId
1 one 20 0
2 two 80 1
3 three 40 2
4 four 50 2
5 five 20 3
6 six 30 3
我要计算所有级别不超过100%
如果我将ID 2的PercentSharing更改为70,则其父级应更新为30,并且如果将用户ID 3或4的任何共享百分比设置为任何其他值,则它应将所有父级用户的共享百分比保持为100%。例如用户ID 3、2、1的总和不应超过100%
我要保持N值或水平的100%比率。
请建议我需要更改表结构吗?
答案 0 :(得分:0)
请考虑以下内容;嵌套模型...
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id CHAR(1) NOT NULL PRIMARY KEY
,pct INT NOT NULL
,lft INT NOT NULL
,rgt INT NOT NULL
);
INSERT INTO my_table VALUES
('A',20,1,12),
('B',80,2,11),
('C',40,3, 8),
('D',50,9,10),
('E',20,4, 5),
('F',30,6, 7);
SELECT * FROM my_table x JOIN my_table y ON y.lft <= x.lft WHERE x.id = 'E';
+----+-----+-----+-----+----+-----+-----+-----+
| id | pct | lft | rgt | id | pct | lft | rgt |
+----+-----+-----+-----+----+-----+-----+-----+
| E | 20 | 4 | 5 | A | 20 | 1 | 12 |
| E | 20 | 4 | 5 | B | 80 | 2 | 11 |
| E | 20 | 4 | 5 | C | 40 | 3 | 8 |
| E | 20 | 4 | 5 | E | 20 | 4 | 5 |
+----+-----+-----+-----+----+-----+-----+-----+
SELECT x.*, SUM(y.pct) total FROM my_table x JOIN my_table y ON y.lft <= x.lft WHERE x.id = 'E' GROUP BY x.id;
+----+-----+-----+-----+-------+
| id | pct | lft | rgt | total |
+----+-----+-----+-----+-------+
| E | 20 | 4 | 5 | 160 |
+----+-----+-----+-----+-------+
1 row in set (0.00 sec)