我正在尝试获取属于某个用户的所有帖子,然后对每个帖子都计算。
在这里,我获取了属于某个用户的所有帖子:
SELECT Posts.id,
Posts.uuid,
Posts.caption,
Posts.path,
Posts.date,
USERS.id,
USERS.username,
USERS.fullname,
USERS.profileImage
FROM A.Posts JOIN A.USERS ON
Posts.id = 145 AND USERS.id = 145 ORDER by date DESC
LIMIT 0, 5
这就是我如何查询每个帖子的喜欢的内容:
SELECT COUNT(uuidPost)
FROM Activity
WHERE type = "like" AND uuidPost = "FA4C8196-CEA3-4373-94B2-59F387BB1906"
不确定如何组合它们?
如果有人可以提供帮助或向我提供有关查询的提示,我将非常感谢您的帮助!
提前致谢!
SELECT Posts.id,
Posts.uuid,
Posts.caption,
Posts.path,
Posts.date,
USERS.id,
USERS.username,
USERS.fullname,
USERS.profileImage,
coalesce(A.LikeCNT,0),
IF( A.uuidPost IS NOT NULL , 1, 0 ) AS CurrentUser
FROM Posts
INNER JOIN USERS
ON Posts.id = 145
AND USERS.id = 145
LEFT JOIN (SELECT COUNT(A.uuidPost) LikeCNT, A.UUIDPost, A.id
FROM Activity A
WHERE type = 'like'
GROUP BY A.UUIDPOST) A
on A.UUIDPost=Posts.uuid
AND A.id = Posts.id
WHERE Posts.id = 145
ORDER BY date DESC
LIMIT 0, 5
答案 0 :(得分:2)
执行此操作的一种方法是使用内联选择...使用相关查询。
SELECT Posts.id,
Posts.uuid,
Posts.caption,
Posts.path,
Posts.date,
USERS.id,
USERS.username,
USERS.fullname,
USERS.profileImage,
(SELECT COUNT(A.uuidPost)
FROM Activity A
WHERE type = 'like'
AND A.uuidPost = Posts.uuid) as LikeCNT
FROM Posts
INNER JOIN USERS
ON Posts.id = 145
AND USERS.id = 145
ORDER BY date DESC
LIMIT 0, 5
虽然我不是大型数据集的忠实粉丝...我通常更喜欢......
SELECT Posts.id,
Posts.uuid,
Posts.caption,
Posts.path,
Posts.date,
USERS.id,
USERS.username,
USERS.fullname,
USERS.profileImage,
coalesce(A.LikeCNT,0)
FROM Posts
INNER JOIN USERS
ON Posts.id = 145
AND USERS.id = 145
LEFT JOIN (SELECT COUNT(A.uuidPost) LikeCNT, A.UUIDPost
FROM Activity A
WHERE type = 'like'
GROUP BY A.UUIDPOST) A
on A.UUIDPost=Posts.uuid
ORDER BY date DESC
LIMIT 0, 5
由于引擎生成计数数据集一次,而不必为每个UUID执行。我们必须使用coalesce作为UUID,因为帖子可能没有喜欢,因此不存在记录,因此左边连接上的空值。所以为了显示0,我们需要取第一个非空值,或者是数字,或者使用0。
--- UPDATE:
您是否意识到您添加的A.ID将是活动表中uuidpost权利的随机ID?
我修改了这个以包括当前用户(145?)通过向子查询中添加一个名为CurrentUserLiked的新列来“喜欢”该帖子。
我不得不假设活动表上userID的列名是UserID;必要时改变它。我还假设当前用户被定义为145,这最终将通过php传递。以及列出的其他两个145。
我不确定您为当前用户尝试使用A.uuidPost,所以我暂时不管它。
SELECT Posts.id,
Posts.uuid,
Posts.caption,
Posts.path,
Posts.date,
USERS.id,
USERS.username,
USERS.fullname,
USERS.profileImage,
coalesce(A.LikeCNT,0),
IF( A.uuidPost IS NOT NULL , 1, 0 ) AS CurrentUser,
A.CurrentUserLiked
FROM Posts
INNER JOIN USERS
ON Posts.id = 145
AND USERS.id = 145
LEFT JOIN (SELECT COUNT(A.uuidPost) LikeCNT, A.UUIDPost, A.id, sum(CASE WHEN A.USERID = 145 then 1 else 0 end) as CurrentUserLiked
FROM Activity A
WHERE type = 'like'
GROUP BY A.UUIDPOST) A
on A.UUIDPost=Posts.uuid
AND A.id = Posts.id
WHERE Posts.id = 145
ORDER BY date DESC
LIMIT 0, 5