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 - 名前 - ページ - 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 に答える