我目前有一个查询,它返回存在的每个帖子的列表,其评论(连接)以及它有多少喜欢。
我想添加一个列,指示用户是否已赞成/喜欢此特定帖子。相关表格的结构如下:
喜欢(id,elementID,googleID)
元素(id,googleID,时间,标题,正文,类型)
评论(id,elementID,googleID,正文)
那么我将如何浏览喜欢的内容,确定其中一个是否具有用户的ID(通过Node.JS动态调入查询),然后创建一个指示简单的真或假的列? / p>
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;
答案 0 :(得分:1)
针对LEFT JOIN
添加likes
,将用户的googleID
传递到加入的ON
子句中。如果来自该连接的值为非null,则用户已喜欢该帖子。如果为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
,但它可能没有此方法那么快。
答案 1 :(得分:1)
添加条件SUM
这将是0
或>0
,以防用户喜欢它。
SELECT
E.id, E.time, E.title, E.body, E.type,
C.comments, E.googleID, L.likeCount, L.user_likeit
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, SUM( CASE
WHEN googleID =@userID THEN 1
ELSE 0
END
) as user_likeit
FROM likes
GROUP BY elementID
) L ON L.elementID = E.id;
我谷歌并发现Conditional Count/Sum in Select看起来也可以工作
sum(googleID = @userID)