我在三个表中有两个查询
表1 =用户价格的hirarchey
+----------+------------+-----------+
| userid | parent | price |
+----------+------------+------------
| 1 | null | 20 |
| 2 | 1 | 20 |
| 3 | 1 | 20 |
| 4 | 2 | 20 |
| 5 | 2 | 20 |
| 6 | 3 | 20 |
| 7 | 4 | 20 |
+----------+------------+-----------+
我需要使用父级1获取所有用户ID,然后通过用户ID和价格获得其他表和组中的后代
+-------------+---------------+-------------+
| ancestor_id | descendant_id | path_length |
+-------------+---------------+-------------+
| 1 | 1 | 0 |
| 1 | 2 | 1 |
| 1 | 3 | 1 |
| 1 | 4 | 2 |
| 1 | 5 | 2 |
| 1 | 6 | 2 |
| 1 | 7 | 3 |
| 2 | 2 | 0 |
| 2 | 4 | 1 |
| 2 | 5 | 1 |
| 2 | 7 | 2 |
| 3 | 3 | 0 |
| 3 | 6 | 1 |
| 4 | 4 | 0 |
| 4 | 7 | 1 |
| 5 | 5 | 0 |
| 6 | 6 | 0 |
| 7 | 7 | 0 |
+-------------+---------------+-------------+
此http://sqlfiddle.com/#!9/9415ed/30适用于死者价格总和
还有另一个表来计算结果先前查询的排名
http://sqlfiddle.com/#!9/b5de18/1
我需要结合两个查询非常感谢
此链接compare result with other table mysql
中有关第二个查询的详细信息两个查询结果工作正常,但第二个查询读取表user_buys,我将user_buys从第一个查询中删除并获取
答案 0 :(得分:0)
如果您要使用嵌套集模型,请大声思考......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,price INT NOT NULL
,lft INT NOT NULL
,rgt INT NOT NULL
);
INSERT INTO my_table VALUES
(1,20,1,14),
(2,20,2,9),
(3,20,10,13),
(4,20,3,6),
(5,20,7,8),
(6,20,11,12),
(7,20,4,5);
SELECT SUM(x.price)
FROM my_table x
JOIN my_table y
ON y.lft < x.lft
AND y.rgt > x.rgt
WHERE y.id = 1;
+--------------+
| SUM(x.price) |
+--------------+
| 120 |
+--------------+