MySQL查询在同一张表上具有2个查询以匹配完全相同的值

时间:2019-02-20 11:58:58

标签: mysql group-by count distinct exact-match

我有一个表,其中包含2个字段,名称和数字。我需要获取名称,其中包含与列表中完全匹配的所有数字。 例如。

details

----------
name | number
----------
A    |   1    
A    |   2    
B    |   1    
C    |   1
D    |   1    
D    |   2   
D    |   3

如果我的列表是(1,2),则输出应仅为A 如果我的列表是(1,2,3),则输出应仅为D 如果我的列表是(1),则输出应为B,C

这是我尝试过的

SELECT name FROM details 
WHERE number IN (1,2) 
GROUP BY name 
HAVING COUNT(DISTINCT number)=2

2 个答案:

答案 0 :(得分:2)

需要考虑的事情:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(name CHAR(1) NOT NULL
,number INT NOT NULL
,PRIMARY KEY(name,number)
);

INSERT INTO my_table VALUES
('A',1),
('A',2),
('B',1),
('C',1),
('D',1),
('D',2),
('D',3);

SELECT *, number IN (1,2) x FROM my_table;
+------+--------+---+
| name | number | x |
+------+--------+---+
| A    |      1 | 1 |
| A    |      2 | 1 |
| B    |      1 | 1 |
| C    |      1 | 1 |
| D    |      1 | 1 |
| D    |      2 | 1 |
| D    |      3 | 0 |
+------+--------+---+

SELECT name
     , COUNT(*)
     , SUM(number IN (1,2)) x 
  FROM my_table 
 GROUP 
    BY name;
+------+----------+------+
| name | COUNT(*) | x    |
+------+----------+------+
| A    |        2 |    2 |
| B    |        1 |    1 |
| C    |        1 |    1 |
| D    |        3 |    2 |
+------+----------+------+

...以防万一它需要说明...

SELECT name
  FROM my_table
 GROUP
    BY name
HAVING COUNT(*) = 2 -- DISTINCT is redundant because of my PRIMARY KEY
   AND COUNT(*) = SUM(number IN (1,2));
;
+------+
| name |
+------+
| A    |
+------+

答案 1 :(得分:1)

尝试使用group_concat

SELECT 
    name
FROM
    (SELECT 
        name, GROUP_CONCAT(number) AS gr
    FROM
        details
    GROUP BY name) a
WHERE
    gr = '1,2';