我正在查找标记为Kane
和Andrew
的客户。
如何将其放入查询?
我希望输出只有
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')
)
答案 0 :(得分:3)
答案 1 :(得分:3)
首先使用client_id
和GROUP 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'
这个是子查询:
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)