假设likes
只能有 1 行具有相同 (user_id,post_id) :
SELECT p.* ,
CASE WHEN
l.id IS NULL THEN 0
ELSE 1
END as is_liked
FROM posts p
LEFT JOIN likes l ON l.user_id = p.user_id and l.post_id =p.post_id
如果不是(likes
给定的 (user_id,post_id) 中的多行):
SELECT p.* ,
CASE WHEN
l.user_id IS NULL THEN 0
ELSE 1
END as is_liked
FROM posts p
LEFT JOIN
(
SELECT DISTINCT user_id,post_id FROM likes
) l ON l.user_id = p.user_id and l.post_id =p.post_id;
或者
SELECT p.* ,
CASE
WHEN EXISTS (SELECT NULL FROM likes l
WHERE l.user_id = p.user_id and l.post_id =p.post_id) THEN 1
ELSE 0
END as is_liked
FROM posts p
更新
我希望我现在对这个问题有更好的理解。我的假设:posts.user_id
是创建帖子的用户的 ID;like
表存储有关谁喜欢该帖子的信息。因此,要检查所有帖子以及您是否需要特定的帖子($login_user_id
应该正确转义)
SELECT p.* ,
CASE
WHEN EXISTS (SELECT NULL FROM likes l
WHERE l.user_id = $login_user_id and l.post_id =p.post_id) THEN 1
ELSE 0
END as is_liked
FROM posts p