我目前有一个查询,它返回一个列表,其中包含每个存在的帖子、它的评论(串联)以及它有多少喜欢。
我想包括一个列,指示用户是否赞成/喜欢这个特定的帖子。相关表的结构如下:
喜欢(id、elementID、googleID)
元素(id、googleID、时间、标题、正文、类型)
评论(id、elementID、googleID、正文)
那么我如何通过点赞,确定其中一个是否有用户 ID(通过 Node.JS 动态输入查询),然后创建一个简单的 true 或 false 指示列?
SELECT E.id, E.time, E.title, E.body, E.type, C.comments, E.googleID, L.likeCount
FROM elements E
LEFT JOIN(
SELECT elementID, GROUP_CONCAT(body SEPARATOR '|-|') AS comments
FROM comments
GROUP BY elementID
) C on C.elementID = E.id
LEFT JOIN (
SELECT elementID, COUNT(id) AS likeCount
FROM likes
GROUP BY elementID
) L ON L.elementID = E.id;
最佳答案
针对 likes
添加一个 LEFT JOIN
,将用户的 googleID
传递到连接的 ON
子句中。如果来自该连接的值非空,则用户喜欢该帖子。如果为 null,则用户没有喜欢它。
请注意,您的第一个子查询连接是不必要的。这可以直接在 SELECT
列表中处理,并通过将所有其他选定的列添加到 GROUP BY
子句(实际上这在 MySQL 中甚至不需要,因为宽容分组的默认行为,但这是一个好习惯,因为其他 RDBMS 需要它)
SELECT
E.id,
E.time,
E.title,
E.body,
E.type,
-- This can be moved to the outer SELECT
GROUP_CONCAT(C.body SEPARATOR '|-|') AS comments,
E.googleID,
L.likeCount,
-- Conditional statement to match non-nulls in the
-- left joined likes table, indicating whether the
-- user has liked the post
CASE
-- has a like, return true
WHEN Luser.id IS NOT NULL THEN true
-- does not have a like, return false
ELSE false
END AS userLiked
FROM elements E
-- Convert this to a plain left join instead of subquery
LEFT JOIN comments C ON C.elementID = E.id
-- Left join against likes, strictly matching the user id
LEFT JOIN likes Luser
ON Luser.elementID = E.id
-- Pass the user id into the join condition.
AND Luser.googleID = <the user's id>
LEFT JOIN (
SELECT elementID, COUNT(id) AS likeCount
FROM likes
GROUP BY elementID
) L ON L.elementID = E.id;
-- Put the other columns into GROUP BY
-- instead of another left join subquery
GROUP BY
E.id,
-- MySQL will let you get by without the rest of these
-- but it is good practice to use them. Other RDBMS would
-- not allow them to be omitted...
E.time,
E.title,
E.body,
E.type,
E.googleID
likeCount,
userLiked
如果您更愿意返回到对 GROUP_CONCAT()
使用您的子查询连接,您可以恢复到那个状态并删除外部 GROUP BY
,但它可能不会和这个方法一样快。
关于mysql - 如何在 MySQL 查询中包含用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32299269/