只有在其他表中不存在用户名时,MySQL才会选择用户名

时间:2014-04-20 11:56:03

标签: mysql sql

我需要为我的系统获取用户名,但如果它们存在于punishement_banned表中,则不会获取该用户名。

我已经做了一个查询,应该做那个工作,但由于某种原因,查询返回0值。

我在punishement_banned中有1行,有1个名字,在player表中共有2个名字,所以它必须显示1行。

SELECT players.username FROM players LEFT JOIN punishement_banned a ON a.username = players.username WHERE players.username != a.username;

但如果我运行此查询,它将显示2个名称:

SELECT players.username FROM players LEFT JOIN punishement_banned a ON a.username = players.username;

我的查询有什么问题?

5 个答案:

答案 0 :(得分:2)

我创建了sqlfiddle:http://www.sqlfiddle.com/#!2/fd650/4/0

SELECT username 
FROM players 
WHERE NOT EXISTS  
(  
   SELECT username 
   FROM punishement_banned 
   WHERE players.username = punishement_banned.username 
)

答案 1 :(得分:1)

这应该做的工作:

SELECT username 
FROM players 
WHERE players.username NOT IN 
(SELECT username FROM punishement_banned)

问题是,你加入用户名相同的表,然后排除彼此相等的用户名。

答案 2 :(得分:0)

你有两个矛盾的条件

   ON a.username = players.username WHERE players.username != a.usernam

你需要使用NOT IN

  SELECT username FROM players 
  WHERE players.username NOT IN (select username from punishement_banned )

答案 3 :(得分:0)

您的语句会找到任何可以与没有该用户名的行匹配的用户名,实际上是任何用户名。

使用此:

SELECT players.username FROM players WHERE players.username NOT IN( SELECT username FROM punishement_banned )

答案 4 :(得分:0)

两种选择:

  1. 使用IN运算符:

    SELECT username 
    FROM players 
    WHERE players.username NOT IN (SELECT username FROM punishement_banned)
    
  2. 使用LEFT JOIN

    如果表中有数千条记录,这将比第一种方法更快。

    SELECT players.username FROM players 
    LEFT JOIN punishement_banned a ON a.username = players.username
    WHERE a.username=NULL