MySQL在哪里而不在

时间:2017-08-31 15:37:15

标签: mysql sql

请问有关如何获得我想要的输出的任何人都可以帮助解决这个问题吗?

我正在寻找有标签"凯恩"但不是"安德鲁"。

我期待输出:

  

"客户3"只因为在"客户1"有一个标签安德鲁

INSERT INTO `client` (`id`, `name`) VALUES
  ('1', 'Client 1'),
  ('2', 'Client 2'),
  ('3', 'Client 3'),
  ('4', 'Client 4');

 INSERT INTO `tag` (`id`, `client_id`, `tag`) VALUES
  ('1', '1', 'Kane'),
  ('2', '1', 'Andrew'),
  ('3', '2', 'Andrew'),
  ('4', '3', 'Kane'),
  ('5', '3', 'James'),
  ('6', '4', 'Andrew');

## mysql query
select * from client where 
exists (
select client_id 
    from tag 
    where tag.client_id = client.id 
    and tag in ('Kane')
    and tag not in ( 'Andrew' )
)

documentation

6 个答案:

答案 0 :(得分:3)

这是一种方式,NOT IN()

SELECT *
FROM Client C
JOIN tag t on C.id = t.client_id
WHERE tag = 'Kane'
AND c.id NOT IN (SELECT client_id FROM tag WHERE tag = 'Andrew')

Fiddle

基本上,您获得拥有tag = 'Kane'的所有客户,然后使用tag = 'Andrew'

删除具有NOT IN()实例的客户

答案 1 :(得分:2)

<强>查询

SELECT 
   client.id
 , client.name
FROM 
 CLIENT 
INNER JOIN 
 tag
ON
 client.id = tag.client_id 
GROUP BY 
   client.id
 , client.name
HAVING 
   SUM(tag = 'Kane')
 AND
   NOT SUM(tag = 'Andrew') 

<强>结果

    id  name      
------  ----------
     3  Client 3

答案 2 :(得分:1)

也许不是最有效的方法,但这可行:

select * from client where 
exists (
select client_id 
    from tag 
    where tag.client_id = client.id 
    and tag in ('Kane')
)
and not exists (
select client_id 
    from tag 
    where tag.client_id = client.id 
    and tag in ('Andrew')
)

您的查询存在的问题是它尝试同时应用tag in ('Kane')     和tag not in ( 'Andrew' )同时对每一行。由于第一个条款是限制性的,因此它使第二个条款变得多余。你必须分别问两个问题。

答案 3 :(得分:1)

这是蛮力方法:

SELECT name
FROM client
WHERE id
IN
(SELECT client_id
 FROM tag
 WHERE tag = 'Kane') 
AND id NOT IN
(SELECT client_id
 FROM tag
 WHERE tag = 'Andrew') 

答案 4 :(得分:1)

这可能是最快的选择。

SELECT c.id, c.name
FROM client AS c
INNER JOIN tag AS t1 ON a.id = t.client_id
LEFT JOIN tag AS t2 ON a.id = t2.client_id AND t2.tag = 'Andrew'
WHERE t1.tag = 'Kane'
AND t2.tag IS NULL
;

答案 5 :(得分:0)

此查询应该适用于您的情况。

 select * from client a
join tag b on a.id = b.client_id
where b.tag = 'Kane'
and not exists
(select * from tag c where c.client_id = b.client_id and tag = 'Andrew' )

当你在连接上有2个冲突的过滤器时,第二个过滤器会与第一个过滤器和冲突相结合。

第二个过滤器存在或不存在解决方案,这样第二个条件就会应用于查询结果,并被视为一个单独的条件。