MySQL IN在同一列上

时间:2017-09-20 10:37:21

标签: mysql mysqli

我正在查找标记为KaneAndrew的客户。

如何将其放入查询?

  

我希望输出只有Client ID 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  = 'Kane' and tag = 'Andrew')
)

http://sqlfiddle.com/#!9/48955/55

3 个答案:

答案 0 :(得分:3)

您可以使用以下查询来获得所需的结果

opt

DEMO

OR

--config opt

DEMO

答案 1 :(得分:3)

首先使用client_idGROUP BY找到同时包含这两个名称的HAVING。然后将其与第一个表连接以获取name

<强>查询

select t1.`name`
from `client` t1
join (
    select `client_id` from `tag`
    where `tag` in ('Kane','Andrew')
    group by `client_id`
    having count(*) = 2
) t2
on t1.`id` = t2.`client_id`;

<强> documentation

答案 2 :(得分:1)

以下是一些没有分组的查询

这只是INNER JOIN

SELECT client.* 
FROM client 
INNER JOIN tag tag1
ON tag1.client_id = client.id
INNER JOIN tag tag2
ON tag2.client_id = client.id
WHERE tag1.tag = 'Kane'
AND tag2.tag = 'Andrew'

Demo

这个是子查询:

SELECT * 
FROM client 
WHERE ( SELECT COUNT(*) > 0 FROM tag WHERE tag.client_id = client.id AND tag.tag = 'Kane')
AND ( SELECT COUNT(*) > 0 FROM tag WHERE tag.client_id = client.id AND tag.tag = 'Andrew')

两个查询都可以从索引中受益

ALTER TABLE tag ADD KEY LOOKUP (tag , client_id)