$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和他/她阅读的书籍数量 books表是这样的:id - name - pages - readby 行readby包含用户id.any想法/建议?我在考虑使用count(),但我不知道该怎么做。
答案 0 :(得分: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];
?>
希望这有帮助! :)
答案 1 :(得分: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.";
}