如何从连接中获取仅在一个表中的数据?

时间:2013-10-24 19:25:46

标签: mysql sql

我有两张桌子:

Table A
Column: username
joe
mike

Table B
Column: username
joe
joe
bob
bob
bob
bob
mike
mike

我想只看到表B中的用户名但不是表A.什么是只给出用户名bob的查询?

顺便说一句,表B可以有多个相同的用户名而表A不能,所以我假设我需要使用GROUP BY

4 个答案:

答案 0 :(得分:0)

select distinct username 
from b 
where username not in (select username from a)

您也可以使用加入

select distinct username 
from b 
left join a on a.username = b.username
where a.username is null

答案 1 :(得分:0)

这个怎么样

SELECT * FROM tableb WHERE NOT EXISTS 
(SELECT * FROM tablea WHERE tableb.username = tablea.username)

答案 2 :(得分:0)

这应该有效

table_a中的用户不在b

SELECT username FROM table_a a   什么不存在(SELECT * FROM table_b b                 WHERE b.username = a.username);

table_b中的用户不在

SELECT  username FROM table_b b
  WHERE NOT EXISTS (SELECT * FROM table_a a
                WHERE b.username = a.username);

答案 3 :(得分:0)

SELECT DISTINCT table2.username
  FROM table1 RIGHT JOIN table2 ON table1.username = table2.username
 WHERE table1.username IS NOT NULL