统计表格中的所有帖子"帖子"关于来自表格"用户"

时间:2017-08-14 13:09:48

标签: php mysql

两个表格 - postsusers
posts.userusers.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;

任何帮助?

4 个答案:

答案 0 :(得分:1)

您需要将GROUP BYLEFT 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

https://www.w3schools.com/sql/sql_count_avg_sum.asp