我要求查询语句我有两个表 第一个表'帖子':
post_id title Userid
1 test 1
另一张桌子是'喜欢'
userid post_id
1 1
我需要单个查询来检查用户是否喜欢这张照片批量选择我的解决方案非常差:
SELECT * FROM `table` WHERE x = x LIMIT 100;
并给它foreach并对每一行进行查询:
foreach($results as $v)
{
$data[1] = $v;
$data[1]['is_like'] = SELECT COUNT(*) FROM likes WHERE userid = 1;
}
1是已登录的用户ID
我需要单个查询来返回post_id,..等,并提交类似于is_like
答案 0 :(得分:1)
假设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
答案 1 :(得分:1)
SELECT
p.post_id,
p.title,
IF(l.post_id IS NOT NULL,1,0) as like
FROM posts as p
LEFT JOIN likes as l ON l.post_id = p.post_id AND l.userid = p.userid
WHERE p.Userid = 1
如果有喜欢的表格中的post_id,则会返回1,否则为0。
答案 2 :(得分:0)
这样的东西应该作为单个查询工作(当然未经测试 - 你没有提供太多数据用于测试):
select
p.title, count(l.post_id)
from
`posts` p
inner join
`likes` l
on
l.userid = p.userid and l.post_id = p.post_id
where
p.userid = loggedinuserID
group by
p.userid
这将为您提供指定用户喜欢的总帖子数。