Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL: How to Count occurrences in TableA, join with TableB and then order by occurences?
    primarykey
    data
    text
    <h3>What I want:</h3> <p>For every User that is connected to Group_ID=1 I want to count the amount of activities this User have attended, and use that info to order by User with the most attendings DESC(ending).</p> <p><em>A table that connects Users to Groups:</em></p> <pre><code>user_r_group: ID User_ID Group_ID 1 1 1 2 3 1 3 2 1 4 1 2 &lt;-- User 1 connected to another group </code></pre> <p><em>A table that shows which activities User have attended:</em></p> <pre><code>activities_attended: ID Activity_ID User_ID 1 1 1 &lt;-- User 1 have attended 3 activities 2 1 3 3 1 2 4 2 1 &lt;-- User 1 have attended 3 activities 5 2 3 6 3 1 &lt;-- User 1 have attended 3 activities </code></pre> <p><strong>The outcome I'm looking for:</strong></p> <pre><code>User_ID Attendings 1 3 3 2 2 1 </code></pre> <h1>Is there a way to write a mysql_query to achieve this?</h1> <p>It sure feels like it. Or will I need to puzzle myself with loops in php with querycombinations?</p> <p>I've checked out ways to <a href="https://stackoverflow.com/q/10060325/2808954">join tables</a>, and I'm slightly familiar with <a href="https://stackoverflow.com/q/2283305/2808954">ORDER BY</a>, but I have no real clue how to store the attendings-info for every User and then order by it, to then put it all together in a query as wanted ;/ A lil help please?</p> <hr> <p><em>Solved it!</em></p> <p>Thanks to <a href="https://stackoverflow.com/users/477127/gordonm">GordonM</a> for guidance on where to look, and thanks to <a href="https://stackoverflow.com/users/1793906/milen-pavlov">Milen Pavlov</a> as well as <a href="https://stackoverflow.com/users/1445460/kirill-fuchs">Kirill Fuchs</a> for the code-samples. I combined the codes into my own prefered version. Kirill's code was however accurate on exception that he forgot the 'ORDER BY Attendings DESC' in the end ;)</p> <pre><code>SELECT COUNT(aa.User_ID) as Attendings, urg.User_ID FROM activities_attended aa INNER JOIN user_r_group urg ON urg.User_ID=aa.User_ID WHERE urg.Group_ID=1 GROUP BY urg.User_ID ORDER BY Attendings DESC </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload