gpt4 book ai didi

php - mysql 返回每个 user_id 的总行数

转载 作者:行者123 更新时间:2023-11-29 04:11:00 26 4
gpt4 key购买 nike

  $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

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

最佳答案

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

编辑 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.";
}

关于php - mysql 返回每个 user_id 的总行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com