我正在使用mysql, 问题是,我有一个像'101'这样的组ID,我希望得到他帐户下的所有设备ID,以及那些属于其子组的id 例如:如果组ID是101:那么 device_id应该是 1.44444 2.33333 3. 55555
Table : Groups --------------------------------------------------------------------------------------
group_id | parent_id | group_name
--------------------------------------------------------------------------------------
101 | null | matrix
102 | 101 | sub_matrix1
103 | 101 | sub_matrix2
104 | null | abc
105 | 104 | sub_abc
106 | null | mega
---------------------------------------------------------------------------------------
Table : Devices
--------------------------------------------------------------------------------------
device_id | group_id | device_name
--------------------------------------------------------------------------------------
44444 | 101 | m1
33333 | 101 | m1
22222 | 102 | m1
55555 | 103 | m1
88888 | 104 | m1
---------------------------------------------------------------------------------------
答案 0 :(得分:1)
这是一篇关于mysql中的分层数据的好文章:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
这样的事可能有用;
SELECT t1.device_name
FROM devices AS t1
INNER JOIN groups AS t2 ON t2.group_id = t1.group_id
WHERE t1.group_id = '101' OR t2.parent_id = '101';