MySQL根据特定的列值获取所有行(按列过滤)

时间:2016-03-29 07:21:45

标签: mysql

我在这里有这张表:

| colA | colB
| 1    | 2
| 2    | 2 
| 3    | 3
| 3    | 2

我想查询colB为3和2的所有行。其中结果为:

|colA  | colB
| 3    | 3
| 3    | 2

我尝试过查询:

select * from A where colB = 2 AND colB= 3

但我一直得到一个空洞的回应。试过OR但它也行不通。我理解我所尝试的是一种“行”过滤。

有没有办法处理“列”过滤?

2 个答案:

答案 0 :(得分:1)

试试这个:

select *
from A
where colA IN (select colA 
               from A 
               where colB IN (2, 3)
               group by colA
               having count(distinct colB) = 2)

或使用JOIN

select A.*
from A 
join (select colA 
      from A 
      where colB IN (2, 3)
      group by colA
      having count(distinct colB) = 2
) as t on A.colA = t.ColA

答案 1 :(得分:1)

您可以使用EXISTS()

SELECT * FROM YourTable a
WHERE EXISTS(SELECT 1 from YourTable s
             WHERE a.colA = s.colA
              and s.colB in(2,3)
             GROUP BY s.colA having count(distinct s.colB) = 2)