cppit
cppit

Reputation: 4564

mysql return the total of rows for each user_id

  $sql = "SELECT * FROM books LEFT JOIN users
           ON books.readby=users.user_id WHERE users.email IS NOT NULL";
  $result = mysql_query($sql);
  while($row = mysql_fetch_array($result))
     {
echo $row['readby']. " - read 10 books";
 } //while ends

this is the code I have so far. I am trying to retrieve the number of books read by each user and echo the results. echo the user_id and number of books he/she read books table is like this : id - name - pages - readby the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.

Upvotes: 1

Views: 146

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270637

A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.

Edit The GROUP BY had been omitted...

SELECT 
  users.*,
  usersread.numread
FROM 
  users
  /* join all user details against count of books read */
  LEFT JOIN  (
    /* Retrieve user_id (via readby) and count from the books table */
    SELECT 
      readby,
      COUNT(*) AS numread
    FROM  books
    GROUP BY readby
  ) usersread ON users.user_id = usersread.readby

In your PHP then, you can retrieve $row['numread'] after fetching the result.

// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
  // don't know the contents of your users table, but assuming there's a 
  // users.name column I used 'name' here...
  echo "{$row['name']} read {$row['numread']} books.";
}

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You can use count() this way:

<?php
    $count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
    $count = $count[0];
?>

Hope this helps! :)

Upvotes: 3

Related Questions