SQL查询返回包含来自另一列的数据的列

时间:2017-03-28 15:40:53

标签: mysql sql database

我有一个表格通知连接到表格喜欢和评论。当我返回用户的通知时,我还创建了列:number_of_likes,number_of_comments和likes_by_me。当进行查询的用户不喜欢通知时,查询正常工作(likes_by_me = 0)。但如果他们有(likes_by_me = 1),我获得的number_of_likes的值是错误的,并且与number_of_comments相同。

示例:

1)
- 我喜欢=假
- likes = 1
- comments = 5

返回值:
- likes_by_me = 0
- number_of_likes = 1
- number_of_comments = 5

2)
- 我喜欢=真实 - likes = 2
- comments = 5

返回值:
- likes_by_me = 1
- number_of_likes = 5
- number_of_comments = 5

以下是我正在使用的查询:

SELECT notices.*
     , count(comment.id) as number_of_comments
     , count(like1.user_id) as number_of_likes
     , like2.user_id IS NOT NULL AS liked_by_me
     , boards.name as board_name
FROM notices
LEFT JOIN comments as comment
   ON (comment.notice_id = notices.id)
LEFT JOIN likes as like1
   ON (like1.notice_id = notices.id)
LEFT JOIN likes as like2
   ON (like2.notice_id = notices.id 
   AND like2.user_id = $1)
LEFT JOIN boards
   ON (boards.id = notices.board_id)
LEFT OUTER JOIN board_users
   ON (board_users.board_id = notices.board_id)
WHERE board_users.user_id = $1
GROUP BY notices.id
       , boards.name
       , like2.user_id
       , userId

任何帮助将不胜感激。我已经在这几个小时了,我不认为我能找到问题。

谢谢!

解决方案: 这是工作查询

SELECT notices.*, 
(SELECT COUNT(user_id) from likes WHERE likes.notice_id = notices.id) AS number_of_likes, 
(SELECT user_id IS NOT NULL from likes WHERE likes.notice_id = notices.id AND likes.user_id = $1) AS liked_by_me, 
count(comments.id) as number_of_comments, boards.name as board_name
FROM notices LEFT JOIN comments ON (comments.notice_id = notices.id) 
LEFT JOIN boards ON (boards.id = notices.board_id) 
LEFT OUTER JOIN board_users ON (board_users.board_id = notices.board_id) 
WHERE board_users.user_id = $1 GROUP BY notices.id, boards.name", user);

1 个答案:

答案 0 :(得分:0)

您必须使用subeselects。

关于此问题的优秀文章: The GROUPing pitfall

TL; DR:基本上,您必须意识到,您的所有评论和喜欢都会彼此倍增。尝试显示查询结果而不使用group子句查看,正在计算重复的likes / comments。

编辑:我没有对此进行测试,但查询的结果如何: (即如果用户只能喜欢一次通知,否则您必须将当前用户的喜欢分组)

SELECT
    notices.*,
    comments.number_of_comments,
    likes.number_of_likes
    current_user_likes.user_id IS NOT NULL AS liked_by_me
    boards.name AS board_name
FROM notices

LEFT JOIN (
    SELECT
        COUNT(*) AS number_of_comments,
        notice_id
    FROM comments
    GROUP BY notice_id
) AS comments ON comments.notice_id = notices.id

LEFT JOIN (
    SELECT
        COUNT(*) AS number_of_likes,
        notice_id
    FROM likes
    GROUP BY notice_id
) AS likes ON likes.notice_id = notices.id

LEFT JOIN likes AS current_user_likes 
    ON current_user_likes.notice_id = notices.id 
        AND current_user_likes.user_id = $1
LEFT JOIN boards ON boards.id = notices.board_id

INNER JOIN board_users 
    ON board_users.board_id = notices.board_id
        AND board_users.user_id = $1;