MySQL查询基于另一个表的条件

时间:2015-10-14 15:58:27

标签: mysql sql not-exists

我正在尝试编写一个MySQL查询,根据从另一个表中评估的条件选择10个用户名。

结果将是10个用户名作为建议。因此,我需要选择当前未被记录用户遵循的10个用户名。

以下内容返回已经关注的用户,因此出现了问题。知道怎么解决这个问题吗?

"SELECT  username
FROM    users
WHERE   NOT EXISTS
        (
        SELECT  id 
        FROM    user_followers
        WHERE   user_followers.user_followed_id = users.username AND user_followers.user_follower_id = ?
        )  
ORDER BY followers DESC LIMIT 10 "

user_followed_id - 从外部查询评估的用户的用户名 user_follower_id - 进行检查的用户的用户名(使用预准备语句)

2 个答案:

答案 0 :(得分:0)

也许尝试LEFT JOIN

  SELECT *
  FROM users  u
  LEFT JOIN user_followers uf
    ON u.username  = uf.user_followed_id 
   AND uf.user_follower_id <> ?

答案 1 :(得分:0)

我希望这有助于:

SELECT  username
FROM    users
WHERE username  NOT EXISTS
    (
    SELECT  user_followers.user_followed_id -- I see in you code below that you use this to store the username 
    FROM    user_followers
    WHERE   user_followers.user_follower_id = ?
    )
AND username <> ?  -- if the parameter is not the username,may be changed by the id column name of the user
ORDER BY followers DESC LIMIT 10