MySQL 连接和来自另一个表的 COUNT(*)
我有两个表:groups
和 group_members
。
groups
表包含每个群组的所有信息,例如 ID、标题、描述等。
在 group_members
表中,它列出了属于该群组的所有成员。每个组都是这样的:
group_id | user_id
1 | 100
2 | 23
2 | 100
9 | 601
基本上,我想在页面上列出三个组,并且我只想列出拥有四个以上成员的组。在 循环内,我想要该组中的四个成员。我在列出组和在另一个内部循环中列出成员时没有遇到任何问题,我只是无法细化组,以便只有那些拥有超过 4 个成员的组才会显示。
有人知道该怎么做吗?我确信它与 MySQL 连接有关。
I have two tables: groups
and group_members
.
The groups
table contains all the information for each group, such as its ID, title, description, etc.
In the group_members
table, it lists all the members who are apart of each group like this:
group_id | user_id
1 | 100
2 | 23
2 | 100
9 | 601
Basically, I want to list THREE groups on a page, and I only want to list groups which have MORE than four members. Inside the <?php while ?>
loop, I then want to four members who are apart of that group. I'm having no trouble listing the groups, and listing the members in another internal loop, I just cannot refine the groups so that ONLY those with more than 4 members show.
Does anybody know how to do this? I'm sure it's with MySQL joins.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
MySQL 使用 HAVING 语句来执行此任务。
您的查询将如下所示:
引用具有不同名称时的示例
另外,请确保在数据库架构内为 JOINS 中使用的键设置索引,因为它会影响您的站点性能。
MySQL use HAVING statement for this tasks.
Your query would look like this:
example when references have different names
Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.
也许我在这里偏离了主题,不理解OP,但你为什么要加入表格?
如果您有一个包含成员的表,并且该表有一个名为“group_id”的列,则您只需对members 表运行查询即可获取按group_id 分组的成员计数。
这应该具有最少的开销,因为您避免了连接,但仍然应该给您您想要的东西。
如果您想要组详细信息和描述等,则将成员表中的联接添加回组表以检索名称将为您提供最快的结果。
Maybe I am off the mark here and not understanding the OP but why are you joining tables?
If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.
This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.
If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.
您的
groups_main
表有一个名为id
的键列。我相信,如果groups_fans
表具有同名的键列,则只能使用USING
语法进行连接,但它可能没有。因此,请尝试以下操作:LEFT JOIN groups_fans AS m ON m.group_id = g.id
或将
group_id
替换为groups_fans< 中适当的列名称/代码>表。
Your
groups_main
table has a key column namedid
. I believe you can only use theUSING
syntax for the join if thegroups_fans
table has a key column with the same name, which it probably does not. So instead, try this:LEFT JOIN groups_fans AS m ON m.group_id = g.id
Or replace
group_id
with whatever the appropriate column name is in thegroups_fans
table.