views:

27

answers:

1

I have a database with two tables, Users and Posts. I'd like to write a php script to list, in order, the top 20 usernames with the number of posts they've made. The username field is cUsername in the Users table. The Users table intUserID field and the Posts table's intPosterID field correspond to eachother.

Any help would be much appreciated. Thanks!

+2  A: 

Use GROUP BY and count. This will get you a list of user IDs to their counts:

SELECT intPosterId, COUNT(*)
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20

You can use the result in a subquery:

SELECT u.cUsername, pcnt.postCount
FROM Users AS u
INNER JOIN (
    SELECT intPosterId, COUNT(*) as postCount
    FROM Posts
    GROUP BY intPosterId
    ORDER BY COUNT(*) DESC
    LIMIT 20
) AS pcnt
ON u.intUserId = pcnt.intPosterId

To use it in a PHP script:

<?php
$sql = '
    SELECT u.cUsername, pcnt.postCount
    FROM Users AS u
    INNER JOIN (
        SELECT intPosterId, COUNT(*) as postCount
        FROM Posts
        GROUP BY intPosterId
        ORDER BY COUNT(*) DESC
        LIMIT 20
    ) AS pcnt
    ON u.intUserId = pcnt.intPosterId
';
$pdo = new PDO(
    'mysql:host=your_host;dbname=your_db', 
    'username', 
    'password',
    array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)
);
$stmt = $pdo->prepare($sql);
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "{$row['cUsername']}: {$row['postCount']} <br />\n";
}
Shabbyrobe
What's the best way to print the results, using echo $results;?
BigMike
I've updated the answer to reflect a PHP based solution to outputting as (fairly ugly) HTML. Is this how you were planning to output it?
Shabbyrobe
Thanks Shabbyrobe. Yes, I just wanted simple html for now. You say fairly ugly, so I assume you wouldn't approach it this way?
BigMike
By the way, this works perfectly. Thanks!
BigMike
No problem! I just meant the output part of it is ugly cos it's mingled in with the DB retrieval logic. The rest of it is nice and neat. I don't like mixing HTML in to echo statements. I'd use some kind of view/code separation like MVC. Have you ever had a play with something like [Twig](http://www.twig-project.org/)?
Shabbyrobe
If it was just a quick and dirty scritp for my own use though, I'd probably just spew it out any old way :)
Shabbyrobe
Never played with Twig. I'll check it out. Thanks very much
BigMike