MySQL joins and COUNT(*) from another table

前端 未结 4 1296
失恋的感觉
失恋的感觉 2020-12-23 19:42

I have two tables: groups and group_members.

The groups table contains all the information for each group, such as its ID, tit

4条回答
  •  囚心锁ツ
    2020-12-23 19:54

    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.

提交回复
热议问题