mysql - Generate SQL query to draw a tree to get users with role_id 1 only
问题描述
Need to get array of all the users with role_id 1 only under a specified users to draw a tree, I have a MLM table which contain the user details and ancestor table which contain all the ancestors ie. parents of the users.
mlm table:
Ancestors table:
ancestor table has role_id of parent in it which is same in the mlm table too. the tree structure will be like this.
Expected output tree stucture:
I have created the tree drawing now i need the users. I placed a field called orders to know the depth.
"SELECT *
FROM mlm
WHERE parent >= " . $id . "
AND role_id = '1'
AND user_id IN (SELECT DISTINCT ans.parent_id AS USER
FROM ancestors ans
INNER JOIN (SELECT user_id
FROM ancestors
WHERE parent_id IN (SELECT user_id
FROM mlm
WHERE parent =
" . $id . "
AND
role_id != '1'))
AS anse
ON ans.user_id = anse.user_id
WHERE ans.role_id = '1'
AND ans.orders = (SELECT Min(ans.orders)
FROM ancestors ans
INNER JOIN (SELECT user_id
FROM ancestors
WHERE
parent_id IN(SELECT user_id
FROM mlm
WHERE parent =
" . $id . "
AND
role_id != '1'))
AS anse
ON
ans.user_id = anse.user_id
WHERE ans.role_id = '1')
ORDER BY ans.orders)
UNION
SELECT *
FROM mlm
WHERE parent = " . $id . "
AND role_id = '1'";
This is the query i currently used but doesn't produce all users with role id 1. The main problem is compressing other users. I may have a user as my grand child which might break the tree.
解决方案
推荐阅读
- jhipster - Angular 2 中的 Typeahead 实现
- android - Android sdk mssing、过期或损坏
- java - 当数字是分数时使用 Java 找到数字的完美 pth 幂
- python-3.x - Python _init_.py
- ios - 检查是否从 UITableViewSection 的每个部分中选择了一个单元格?
- android - Volley JsonObject 请求(方法获取)不起作用
- python-3.x - python问题打印可被a整除的元素数
- mysql - MySQL 中的 CPU 利用率有时会非常高
- javascript - 在客户端 javascript 中创建 TCP/IP 套接字
- vim - 如何使用 Bear 和 make 自动创建 json 编译数据库?