[英]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?
回显user_id和他/她读过的书的书数表,如下所示:id-名称-页面-readby readby行包含用户id。任何想法/建议? I was thinking about using count() but Im not sure how to go about doing that.
我当时正在考虑使用count(),但我不确定该怎么做。
You can use count()
this way: 您可以通过以下方式使用
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];
?>
Hope this helps! 希望这可以帮助! :)
:)
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... 编辑
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
In your PHP then, you can retrieve $row['numread']
after fetching the result. 然后,在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.";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.