我正在开展一个项目,我需要让所有喜欢该帖子的用户及其用户名和其他信息。
我尝试创建一个像这样的连接查询
$sql = "SELECT U.id AS userid, U.name AS NAME, U.username AS username,
U.verified AS verified, U.private AS private,
COUNT(IFOLLOW.user_id) AS i_follow,
COUNT(FR.user_id) AS requested
FROM posts AS P
LEFT JOIN likes AS L ON L.post_id = :postid
LEFT JOIN users AS U ON U.id = L.user_id
LEFT JOIN followers AS IFOLLOW
ON IFOLLOW.user_id = :userid AND IFOLLOW.following_id = U.id
LEFT JOIN follow_requests AS FR
ON FR.requester = :userid AND FR.user_id = U.id WHERE P.id = :postid";
我使用COUNT()
计算用户是否关注/请求关注正在查看喜欢列表的用户。如果它表示1则意味着如果0没有则它们跟随/请求它们。问题是,当我包含count方法时,它将返回它作为一个结果。当我不包括计数时它会返回多个,所以我可以通过它们运行foreach
。
我做错了什么才能把它作为一个结果?
答案 0 :(得分:1)
如果要聚合分区而不是整个表,则应添加GROUP BY
子句。尝试添加
GROUP BY U.id, U.name, U.username, U.verified, U.private
在您的查询结束时。