查询选择帖子并标记当前用户是否喜欢其中一些帖子

时间:2017-05-03 16:52:45

标签: mysql sql database select

我有3张桌子:userpostlike。当我从post选择帖子时,我需要标记其中一个帖子是否已被user.id = 1所喜欢。就像在社交网络中,您已经喜欢的Feed上的帖子 - 标记。但我是数据库的新手,并且不明白我如何更新我的查询以标记user.id = 1是否喜欢帖子。

我当前的选择如下:

SELECT post.id, post.text, post.datetime, user.username,
    (SELECT COUNT(userId) FROM `like` WHERE postId = post.id) AS likes
                    FROM post
                      INNER JOIN user ON user.id = post.authorId;

我还编写了一个查询,以likeuser.idpost.id中选择数据,但不知道如何加入我的两个选项并标记帖子:

SELECT * from `like` as lk where lk.userId = 1 and lk.postId = 5;

我当前的第一个查询结果是:

{
    "username": "monica",
    "datetime": "2017-05-02T16:11:31.000Z",
    "id": 3,
    "likes": 2,
    "text": "Do pariatur anim aliqua adipisicing sit non."
}

但我需要,如果我要求发帖为user.id = 1:

{
    "liked": true, // means that user.id == 1 already liked the post
    "username": "monica",
    "datetime": "2017-05-02T16:11:31.000Z",
    "id": 3,
    "likes": 2,
    "text": "Do pariatur anim aliqua adipisicing sit non."
}

我的桌子:

CREATE TABLE IF NOT EXISTS user (
    id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(15),
    // ...
);

CREATE TABLE IF NOT EXISTS post (
    id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
    text VARCHAR(500),
    authorId INT UNSIGNED,
    // ...
);

CREATE TABLE IF NOT EXISTS `like` (
  postId INT UNSIGNED,
  userId INT UNSIGNED,
  PRIMARY KEY (postId, userId)
);

1 个答案:

答案 0 :(得分:2)

我有点生疏,所以可能有一种更有效的方法来做到这一点,但它有效,你可以根据需要调整它。如果当前用户喜欢它以及有多少人喜欢它,以下内容将获取所有帖子和每个帖子标记:

SELECT 
  exists(select 1 from `like` li where li.postId = p.id and li.userId = u.id limit 1) as liked
  , u.username
  , p.id as postId
  , p.text
  , (select count(distinct l.userId) from `like` l where l.postId = p.id) as liked
FROM
  user u,
  post p
WHERE
  u.id = 2;