两个表格 - posts
和users
列posts.user
与users.id
匹配
我想以这种方式统计所有用户的所有帖子:
user1 5
user2 3
user3 9
...等等意味着来自user1
的{{1}}有来自users
的5个实例......等等。
posts
结果
$items = '';
$sql = "select users.name, posts.user from users inner join posts on users.id = posts.user";
$stmt = $db->query($sql);
while($row = $stmt->fetch()){
$count = $stmt->rowCount();
$items .= "<div><span class='spanuser'>" . $row['name'] . "</span> <span class='spancount'>" . $count . "</span></div>";
}
echo $items;
任何帮助?
答案 0 :(得分:1)
您需要将GROUP BY
与LEFT JOIN
一起使用,例如:
SELECT u.name, COUNT(p.id) AS `count`
FROM users u LEFT JOIN posts p ON u.id = p.user
GROUP BY u.name;
这将为您提供所需的输出。
<强>更新强>
根据我们的讨论,为了获得今天的计数,您可以使用以下查询:
SELECT u.name, COUNT(p.id) AS `count`
FROM users u LEFT JOIN posts p ON u.id = p.user
WHERE DATE(datetime) = DATE(NOW())
GROUP BY u.name;
同样,您可以使用BETWEEN
运算符来获取日期范围的相同计数,例如,过去7天,您可以使用此代码:
SELECT u.name, COUNT(p.id) AS `count`
FROM users u LEFT JOIN posts p ON u.id = p.user
WHERE DATE(datetime) BETWEEN DATE_ADD(NOW(), INTERVAL -7 DAY) AND DATE(NOW())
GROUP BY u.name;
此外,您需要更新php
以使用查询返回的count
,而不是rowCount
,例如:
$items .= "<div><span class='spanuser'>" . $row['name'] . "</span> <span class='spancount'>" . $row['count'] . "</span></div>";
答案 1 :(得分:1)
尝试使用Count()
$items = '';
$sql = "SELECT u.name,COUNT(p.user) as pCount FROM users u INNER JOIN posts p on u.id = p.user GROUP BY u.name";
$stmt = $db->query($sql);
while($row = $stmt->fetch()){
$items .= "<div><span class='spanuser'>" . $row['name'] . "</span> <span class='spancount'>" . $row['pCount'] . "</span></div>";
}
echo $items;
答案 2 :(得分:0)
您希望按用户分组并计算帖子数量,以获得您想要的最终总行数WITH ROLLUP
,例如
SELECT COALESCE(User,'TOTAL') AS Name,
Count(Post.ID) AS CountOfPosts
FROM Users
LEFT JOIN Posts ON Posts.USer= Users.id
GROUP BY Users.id WITH ROLLUP
&#34;总计&#34; row实际上具有null值,因此我们使用COALESCE
将null更改为TOTAL
答案 3 :(得分:0)
尝试使用COUNT()。要计算posts.user