我想显示用户发布的帖子数量,但我有一些不同的表格,需要匹配ID并计算它们。
这样的事情:
用户表
userid username email regdate
34 mister email@some.tld 2013-10-26 12:01:07
帖子表
postid creator post_comment post_title status
1 34 This is comment Post 1 published
2 12 This is comment Post 2 published
3 34 This is comment Post 3 pending
4 25 This is comment Post 4 published
5 34 This is comment Post 5 published
现在我已经有了一个查询,我从users表中选择了有关特定用户的所有数据:
mysqli_query($conn, "SELECT * FROM users WHERE userid = $userid");
$ userid是当前登录用户的ID。这样可以正常工作:它选择有关该用户的所有相关信息。
但我想显示每个用户发布的帖子数量。我在w3schools的某处读过SQL COUNT
函数的工作原理如下:
mysqli_query($conn, "SELECT COUNT(creator) AS userposts FROM posts WHERE creator=$userid");
但是,正如您在发布的表格示例中所见,在5个帖子中,3个来自用户34,其中1个未发布。
我不知道如何创建一个SQL查询来选择userid与$ userid匹配的所有用户,然后从帖子中选择创建者和状态,并计算创建者为$ userid且状态已发布的帖子数。
这是我最终的目标:
用户先生已发布2篇帖子。
答案 0 :(得分:1)
为了只获得已发布帖子的数量,您应该通过ANDing status = 'published'
重构条件语句
mysqli_query($conn, "SELECT COUNT(creator) AS num_posts FROM posts
WHERE creator=$userid AND status = 'published'");
答案 1 :(得分:0)
SELECT COUNT(creator) AS userposts FROM posts p
LEFT JOIN users u ON p.creator=u.userid
WHERE creator=$userid AND status='published'
答案 2 :(得分:0)
正如您在评论中提到的,所有查询都是:
SELECT users.*, COUNT(creator) AS userposts FROM users u
LEFT JOIN posts p ON p.creator = u.userid
WHERE p.creator = $userid AND p.status = 'published'