Display records in order according to the quantity you have in a table

Asked

Viewed 22 times

0

I have two tables in the database, one is saved all the groups and the other the members of the groups. I want to make a page of Popular Groups, would display the groups that have more members in order of quantity. Because it’s two tables I don’t know how I could do it. What I’ve written so far:

<?php 
//Seleciona todos os grupos
$sql = $pdo->query('SELECT * FROM groups');
while($row = $sql->fetch()){

//Conta a quantidade de membros que tem em cada grupo 
$sql_count = $pdo->query('SELECT * FROM group_memberships WHERE group_id = ?', 
             [$row['id']]);
?>
  • 2

    Maybe you can do it directly in SQL with SELECT group_id, count(*) FROM group_memberships GROUP BY group_id ORDER BY 2 DESC;.

  • But then in the case is selecting only the members. I don’t understand very well what exactly this query does.

  • Now I get it, thanks friends <3

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.