1
  $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

这是我到目前为止的代码。我正在尝试检索每个用户阅读的书籍数量并回显结果。回显 user_id 和他/她读过的书的数量表是这样的: id - name - pages - readby 行 readby 包含用户 id。有什么想法/建议吗?我正在考虑使用 count() 但我不确定如何去做。

4

2 回答 2

3

你可以count()这样使用:

<?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];
?>

希望这可以帮助!:)

于 2012-06-23T02:35:15.590 回答
3

子查询可以返回每个用户阅读的书籍数。这与主表左连接以检索有关每个用户的其他列。

编辑GROUP BY被省略...

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

然后,在您的 PHP 中,您可以$row['numread']在获取结果后进行检索。

// 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.";
}
于 2012-06-23T02:42:28.863 回答