0

我要求查询语句我有两个表第一个表'posts':

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 一样归档

4

3 回答 3

3

假设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
于 2013-01-19T17:22:26.317 回答
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

如果 likes 表中的 post_id 可用,它将返回 1,否则返回 0。

于 2013-01-19T18:13:25.093 回答
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

这将为您提供指定用户喜欢的帖子总数的计数。

于 2013-01-19T18:04:30.413 回答