MYSQL,如何检索具有多个具有条件的相同值的行

时间:2015-02-12 12:56:22

标签: mysql

我在MySql中有一个表,其中有一些数据如下:

    name      value2   
+---------+------------+
  cust A      1        
  cust A      0         
  cust B      0         
  cust B      0         
  cust C      0         
  cust D      0         
  cust D      1         
  cust E      1         
  cust E      1  

我想要的结果如下:

  name      value2   
+---------+------------+
  cust B      0        
  cust C      0   

我在下面尝试过查询,但它不起作用:

SELECT * 
  FROM table 
 WHERE name IN(SELECT * FROM table WHERE value2 = 0 GROUP BY name) 

请帮忙。谢谢。

3 个答案:

答案 0 :(得分:0)

这是一种方法,使用带有group by子句的having

select name, 0 as value2
from table t
group by name
having max(value2) = 0;

答案 1 :(得分:0)

这是另一种方式,不使用group byhaving ...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(12) NOT NULL,value2   TINYINT NOT NULL);

INSERT INTO my_table (name,value2) VALUES
('cust A',1),
('cust A',0),
('cust B',0),
('cust B',0),
('cust C',0),
('cust D',0),
('cust D',1),
('cust E',1),
('cust E',1);  

SELECT DISTINCT x.name
              , x.value2 
           FROM my_table x 
           LEFT 
           JOIN my_table y 
             ON y.name = x.name 
            AND y.value2 = 1 
          WHERE x.value2 = 0 
            AND y.id IS NULL;
+--------+--------+
| name   | value2 |
+--------+--------+
| cust B |      0 |
| cust C |      0 |
+--------+--------+

答案 2 :(得分:0)

select name, value2 from table t where value2 = 0 group by name;

你是对的。上述查询不会消除'cust D'。 要消除'cust D',您可以使用如下所示的having子句:

select name, value2 from table t where value2 = 0 group by name having count(value2) > 1;