仅当in子句中的值存在时才返回值

时间:2018-09-18 21:54:19

标签: mysql sql

好吧,老实说,我的标题不正确,但是这就是我解释问题的方式。

这是我的示例数据:

id diagnosis symptom
 1 a          c
 2 a          a
 3 a          b
 6 b          a
 7 b          c

我的问题是我如何仅凭in子句中的条件来检索诊断?

这是我的查询:

SELECT diagnosis 
FROM vdoc_b_symptom
WHERE symptom IN ('a','c')
GROUP BY diagnosis 
HAVING COUNT(*) = 2;

我想要得到的输出仅为b,但是它给了我两个输出。如何仅从症状为aa的症状的“诊断”列中获取c的值? 对不起,我的英语太糟糕了。

enter image description here

3 个答案:

答案 0 :(得分:2)

您可以尝试在HAVING

中使用条件

模式(MySQL v5.6)

CREATE TABLE vdoc_b_symptom(
  diagnosis varchar(5),
  symptom varchar(5)
);

insert into vdoc_b_symptom values ('a','a');
insert into vdoc_b_symptom values ('a','b');
insert into vdoc_b_symptom values ('a','c');
insert into vdoc_b_symptom values ('b','a');
insert into vdoc_b_symptom values ('b','c');

查询#1

SELECT 
        diagnosis
    FROM 
        vdoc_b_symptom
    GROUP BY 
          diagnosis
    HAVING 
        COUNT(distinct symptom) = 2 
    AND 
        SUM(symptom = 'a') > 0 
    AND 
        SUM(symptom = 'c') > 0;

| diagnosis |
| --------- |
| b         |

View on DB Fiddle

答案 1 :(得分:1)

请尝试以下查询。

SELECT DISTINCT diagnosis
FROM vdoc_b_symptom v
WHERE NOT EXISTS (
    SELECT 1
    FROM vdoc_b_symptom
    WHERE diagnosis = v.diagnosis AND symptom NOT IN ('a', 'c')
)

答案 2 :(得分:0)

执行此操作的方法可能更聪明,但据我所知,您需要得到以下结果:1)同时具有'a'和'c'症状,以及2)没有其他任何症状。这样做:

SELECT * 
FROM   vdoc_b_symptom 
WHERE  diagnosis IN (SELECT diagnosis 
                     FROM   vdoc_b_symptom 
                     WHERE  symptom IN ( 'a', 'c' ) 
                     GROUP  BY diagnosis 
                     HAVING Count(*) = 2) 
       AND diagnosis NOT IN (SELECT diagnosis 
                             FROM   vdoc_b_symptom 
                             WHERE  symptom NOT IN ( 'a', 'c' )) 

应该做到这一点。不过,可能需要命名一些表并限定列。