mysql count其他表,MySQL连接和COUNT(*)从另一个表

这篇博客探讨了如何通过MySQL查询从groups和group_members表中筛选出成员数超过四人的小组。解决方案建议使用HAVING子句来过滤结果,查询会显示每个小组的ID及其成员数量,并只列出成员数大于4的小组。
摘要由CSDN通过智能技术生成

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.

解决方案

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members

FROM groups AS g

LEFT JOIN group_members AS m USING(group_id)

GROUP BY g.group_id

HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members

FROM groups AS g

LEFT JOIN group_members AS m ON g.id = m.group_id

GROUP BY g.id

HAVING members > 4

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值