mysql - MySQL 中具有父 ID 的多用户级别

标签 mysql

我有如下 4 级用户表

user_id parent_id
1       NULL
2       1
3       2
4       2
5       3
6       1

我想选择某个父 ID 下的所有用户,例如 user_id = 1,在这种情况下应返回如下结果:

user_id  parent_id
2        1         // return because parent_id = 1
6        1         // return because parent_id = 1
3        2         // return because parent_id of 2 is 1
4        2         // return because parent_id of 2 is 1
5        3         // return because parent_id of 3 is 2

通过提供一个 id,查询是什么?

提前致谢!

最佳答案

试试这个::

    Select 
user_id 
from 

my_table 
where parent_id in 
(
Select 
user_id 
from my_table where parent_id in 
(Select user_id from my_table where parent_id in(Select user_id from my_table where parent_id =?)))

关于mysql - MySQL 中具有父 ID 的多用户级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13697853/

相关文章:

mysql - 选择具有三个最大值的组

mysql - 在 mysql 中,如何找到 id 未在表中任何其他行中引用的行?

查询中的 PHP 函数

mysql - 是否可以在带有 group by 子句的查询结果中指定代表组的行的选择?

mysql - Mysql 连接表中的一列不受 WHERE 子句影响

mysql - 如何清理或随机化敏感的数据库字段

MySql 最大内存过高,仍要求增加

MySQL 行和列选择

php - 可捕获的 fatal error : Object of class mysqli could not be converted to string in what is ment buy it beind an object?

mysql - 对 MySQL 表进行分区后创建索引?