通过自检来提取特定数据

时间:2015-10-01 12:44:36

标签: mysql

我有这样的数据表:

+-------------+------------+------------+  
| Name        | Test1      | Test2      |
+-------------+------------+------------+  
| A           | 1          |   1        |
+-------------+------------+------------+
| A           | 1          |   1        |
+-------------+------------+------------+    
| A           | 0          |   2        |
+-------------+------------+------------+
| B           | 1          |   1        |
+-------------+------------+------------+
| B           | 2          |   1        |
+-------------+------------+------------+    
| C           | 1          |   1        |
+-------------+------------+------------+
| C           | 1          |   1        |
+-------------+------------+------------+    

我需要获得所有在test1和test2值为1的所有名称。

在这种情况下,输出应该是:

+-------------+------------+    
| C           | PASS       |
+-------------+------------+    

因为所有名称为C并且Test1 = 1且Test2 = 1的记录都被传递, 例如,记录A无法通过,因为其中一行的Test1 = 0且Test = 2。 同样适用于B. B只有一条记录,其中Test1 = 1且Test2 = 1但B的下一条记录的Test1 = 2且Test2 = 1.

如何进行可以提取这些数据的查询?或者通过代码解决这个问题更好?

3 个答案:

答案 0 :(得分:1)

我的想法是首先选择不符合规则的名称,然后选择所有剩余的名称。这是你的逻辑吗?

select distinct name, 'PASS' from table
where name not in
(select name from table where test1 <> 1 or test2 <> 1);

答案 1 :(得分:1)

Test1Test2列与UNION结合使用 然后选择最小和最大测试值均为1的name

<强>查询

select name,'PASS' as `status`
from
(
    select name,test1 as test
    from tests
    union all
    select name,test2 as test
    from tests
)t
group by name 
having max(t.test) = 1
and min(t.test) = 1;

SQL Fiddle

答案 2 :(得分:0)

SELECT DISTINCT name, "PASS" FROM yourtable WHERE test1 = 1 AND test2=1