mysql multiple where子句不起作用

时间:2015-03-17 11:32:05

标签: mysql

基于此表

 key    sampleID     rs         A1       A2  
 1     12345       rs123      C        C
 2     12345       rs345      C        C
 3     11110       rs123      C        C
 4     11110       rs345      C        A

本声明

SELECT sampleID 
FROM QS_base 
WHERE (rs = 'rs123' AND A1 = 'C' AND A2 = 'C') 
OR (rs = 'rs345' AND A1 = 'C' AND A2 = 'C')

返回

12345
12345
11110

这句话

SELECT sampleID 
FROM QS_base 
WHERE (rs = 'rs123' AND A1 = 'C' AND A2 = 'C') 
AND (rs = 'rs345' AND A1 = 'C' AND A2 = 'C')

不返回任何记录。我希望它能够回归

 12345
 12345

为什么重新调整没有结果,是否有办法编写它以便可以获得上述结果?

4 个答案:

答案 0 :(得分:1)

AND需要同时满足条件,并且找不到具有2种不同条件的行。

您可以使用exits来执行此操作

select t1.sampleID 
from QS_base  t1
where 
t1.rs = 'rs123' AND t1.A1 = 'C' AND t1.A2 = 'C' 
and exists
(
 select 1 from QS_base t2 where t1.sampleID = t2.sampleID
 and t2.rs = 'rs345' AND t2.A1 = 'C' AND t2.A2 = 'C'
)

答案 1 :(得分:1)

您可以使用group byhaving获得所需内容:

SELECT sampleID 
FROM QS_base 
WHERE (rs = 'rs123' AND A1 = 'C' AND A2 = 'C') OR
      (rs = 'rs345' AND A1 = 'C' AND A2 = 'C')
GROUP BY sampleID
HAVING COUNT(DISTINCT rs) = 2;

答案 2 :(得分:0)

您正在寻找rs为'rs123'和'rs345'的样本。该查询仅单独查看行。

答案 3 :(得分:0)

您在第二个示例中排除了条件。 where子句:

WHERE (rs = 'rs123' AND A1 = 'C' AND A2 = 'C')  AND (rs = 'rs345' AND A1 = 'C' AND A2 = 'C')
云写成:

WHERE rs = 'rs123' AND rs = 'rs345' AND A1 = 'C' AND A2 = 'C'

rs在sime时间不能等于rs123和rs345。 :)

关于你问题的第二部分,是的,它当然可以返回你需要的结果。只需写下:

WHERE (rs = 'rs123' AND A1 = 'C' AND A2 = 'C')

我假设您对此查询有其他要求,如果是,请在您的帖子中说明。