MySQL 跨表嵌套集模型计数
我有一个使用嵌套集模型类来组织数据的应用程序,但是我正在尝试编写一个查询来计算每个组中的总人数。
表:person_to_group
----+------------+-----------
|ID | Person_ID | Group_ID |
----+------------+-----------
| 1 | 3 | 1 |
| 2 | 3 | 2 |
| 3 | 5 | 2 |
| 4 | 7 | 3 |
----+------------+-----------
表:groups
----------+--------------+--------------+-------------
|Group_ID | Group_Name | Group_Left | Group_Right |
----------+--------------+--------------+-------------
| 1 | Root | 1 | 6 |
| 2 | Node | 2 | 5 |
| 3 | Sub Node | 3 | 4 |
----------+--------------+--------------+-------------
我的查询将在列出所有组名称的 while 循环内运行。
我正在尝试实现这样的结果:
Root - Members (3) <-------- 请注意,我希望将子组包含在计数中,并且我不希望将成员计数超过一次。
任何帮助将不胜感激!
I have an application that uses a nested set model class to organise my data, however I'm trying to write a query that will count the total amount of people in each group.
table: person_to_group
----+------------+-----------
|ID | Person_ID | Group_ID |
----+------------+-----------
| 1 | 3 | 1 |
| 2 | 3 | 2 |
| 3 | 5 | 2 |
| 4 | 7 | 3 |
----+------------+-----------
table: groups
----------+--------------+--------------+-------------
|Group_ID | Group_Name | Group_Left | Group_Right |
----------+--------------+--------------+-------------
| 1 | Root | 1 | 6 |
| 2 | Node | 2 | 5 |
| 3 | Sub Node | 3 | 4 |
----------+--------------+--------------+-------------
My query will be run within a while loop which lists all the group names.
I'm trying to accomplish a result like this:
Root - Members (3) <------- Notice that I want subgroups to be included in the count, and I don't want members to be counted more than once.
Any help would be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您在带有组名称的 while 循环内运行它,因此您可能可以获得该组的左值和右值,并将它们放入此查询中:
这适用于给定组。如果您想获得一个查询中每个组的成员计数的完整列表,则必须使用类似以下内容的内容:
但是,我认为第一个在 sql 之外使用循环的解决方案会更有效。
Since you run it inside a while loop with group names you can probably get the group's left and right values instead and put them into this query:
This works for a given group. If you wanted to get a full list of groups with member count for each in one query you would have to use something like:
However I think the first solution with a loop outside of sql would be more efficient.