当我使用WHERE IN条件时,SQL查询用户名不会出现

时间:2015-05-13 05:50:33

标签: mysql sql

我想显示我关注的所有用户帖子以及我自己的帖子。

但我的查询和username结果存在问题:执行后,我正确地收到帖子,但用户详细信息错误。它显示了所有帖子的相同用户详细信息。我怀疑我的WHERE ... IN条款是错误的。

SELECT u.username,
       u.NAME,
       u.profile_pic,
       up.*
FROM   USER u,
       user_post up
WHERE  up.user_id IN ( (SELECT follow_id
                        FROM   follow
                        WHERE  follow_id = $user_id), $user_id )
       AND description = ''
ORDER  BY postime DESC 

如何获取相关用户的user_post

3 个答案:

答案 0 :(得分:0)

您错过了在where语句

中添加外键约束
SELECT u.username,u.name,u.profile_pic, up.* FROM user u, user_post 
up where up.user_id = u.id and up.user_id in (SELECT follow_id FROM follow WHERE follow_id=$user_id) AND description='' order by postime desc

答案 1 :(得分:0)

user和user_post之间没有连接条件。如果你使用了JOIN语法,那么解析器就会抱怨缺少ON。

(在您发表评论后我将IN添加回来):

SELECT u.username,u.name,u.profile_pic, up.* 
FROM user u JOIN user_post up 
  ON up.user_id = u.id
WHERE 
   (up.user_id  = $user_id 
    OR
    up.user_id IN (
                     SELECT user_id 
                     FROM follow 
                     WHERE follow_id=$user_id
                   )
   )
AND description='' 
ORDER BY postime DESC

答案 2 :(得分:0)

您没有在子查询中提及任何user_post ..(SELECT follow_id FROM跟随WHERE follow_id = $ user_id)

因此,在用户表中使用内部联接.. SELECT follow_id FROM跟随内部联接user_post up on follow_id = up.user_id

试试这个:

SELECT  u.username,
        u.name,
        u.profile_pic,
        up.* 
FROM    user u,user_post up 
where   up.user_id in 
(SELECT follow_id FROM follow inner join user_post up follow_id=up.user_id) 
AND    description=''
order by postime desc