Domanda

Ho due tabelle: groups e group_members.

La tabella groups contiene tutte le informazioni per ciascun gruppo, come ID, titolo, descrizione, ecc.

Nella tabella group_members, elenca tutti i membri che fanno parte di ogni gruppo in questo modo:

group_id | user_id
1 | 100
2 | 23
2 | 100
9 | 601

Fondamentalmente, voglio elencare TRE gruppi su una pagina e voglio solo elencare i gruppi che hanno PIU 'di quattro membri.All'interno del ciclo <?php while ?>, voglio quindi quattro membri che fanno parte di quel gruppo.Non ho problemi a elencare i gruppi e a elencare i membri in un altro ciclo interno, semplicemente non riesco a perfezionare i gruppi in modo che vengano visualizzati SOLO quelli con più di 4 membri.

Qualcuno sa come farlo?Sono sicuro che sia con i join di MySQL.

È stato utile?

Soluzione

MySQL utilizza l'istruzione HAVING per queste attività.

La tua query sarà simile a questa:

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

esempio quando i riferimenti hanno nomi diversi

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

Inoltre, assicurati di impostare gli indici all'interno dello schema del database per le chiavi che stai utilizzando in JOINS poiché possono influire sulle prestazioni del tuo sito.

Altri suggerimenti

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_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 the groups_fans table.

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.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top