Mysql组合查询逻辑

时间:2017-04-12 19:10:35

标签: mysql

我有一个包含名称和ID的表名任务。用户使用不同的ID工作。 我想要那些用户名如果​​用户同时使用ID 6和0,或者用户同时使用ID 6或1。

Name    | ID
========|======
Vivek   | 6
Vivek   | 0
Vivek   | 1
Sumit   | 1
Sumit   | 0
Anshul  | 6
Anshul  | 1
Gourav  | 1
Gourav  | 0
Gourav  | 6
Neha    | 6

根据我的问题,我想回答

名称

的Vivek
Anshul
古拉夫

4 个答案:

答案 0 :(得分:1)

SELECT Name
  FROM task
 WHERE ID IN ( 6,1) 
GROUP BY name
HAVING COUNT(*) >= 2
UNION   
SELECT Name
  FROM task
WHERE ID IN ( 6,0 ) 
GROUP BY name
HAVING COUNT(*) >= 2
;

答案 1 :(得分:1)

试试这个:

SELECT name
FROM user
WHERE id in (6,0)
GROUP BY name
HAVING COUNT(DISTINCT(ID)) >= 2

UNION

SELECT name
FROM user
WHERE id in (6,1)
GROUP BY name
HAVING COUNT(DISTINCT(ID)) >= 2

答案 2 :(得分:0)

您需要使用group by并检查count()

select Name
from task
where id in (6,1)
group by name
having count(id) = 2

答案 3 :(得分:0)

SELECT `name` 
FROM `task` 
WHERE (`id` = 1 AND `id`= 6) OR (`id` = 0 AND `id`= 6)
GROUP BY `name` ;