2015-10-14 89 views
0

我想写一个MySQL查询,根据从另一个表中评估的条件选择10个用户名。MySQL查询基于另一个表的条件

结果将有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 - 的用户的用户名到检查时(使用预处理语句)

+0

我想你可能想使用'NOT IN'子句代替'NOT EXISTS',看看它是否有效。 – Maximus2012

+0

如果你可以用你拥有的表格结构来更新你的问题,这也会很有帮助。 – Maximus2012

+2

'user_followers.user_followed_id = users.username'比较id和用户名?怎么样? – FiftyStars

回答

0

也许尝试LEFT JOIN

SELECT * 
    FROM users u 
    LEFT JOIN user_followers uf 
    ON u.username = uf.user_followed_id 
    AND uf.user_follower_id <> ? 
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