修改此SQL语句

时间:2017-02-06 12:25:29

标签: mysql sql

SELECT K.OBJECT_ID, K.`TYPE`
FROM KB_OBJECT_IDENTIFIERS K
WHERE K.`TYPE` IN ('ISSN', 'ISBN') 
GROUP BY K.OBJECT_ID
HAVING count(K.OBJECT_ID) = 2;

在像这样的表

OBJECT_ID   TYPE
1              ISSN
1              ISBN
2              ISSN
2              ISSN

我需要结果显示两个数字为1的对象,因为它们同时具有ISSN和ISBN,但对象ID的行不是数字2,因为它们都是ISSN。

目前我的查询将显示第一条记录(仅一次),它也会显示第二条记录。

3 个答案:

答案 0 :(得分:0)

select * from KB_OBJECT_IDENTIFIERS
where OBJECT_ID in 
(
    SELECT K.OBJECT_ID
    FROM KB_OBJECT_IDENTIFIERS K
    WHERE K.`TYPE` IN ('ISSN', 'ISBN') 
    GROUP BY K.OBJECT_ID
    HAVING count(distinct K.OBJECT_ID) = 2
)

答案 1 :(得分:0)

我认为group by是最简单的方法。我认为exists是:

select k.*
from KB_OBJECT_IDENTIFIERS k
where exists (select 1
              from KB_OBJECT_IDENTIFIERS k2
              where k.object_id = k2.object_id and
                    k.type <> k2.type
             );

编辑:如果还有其他类型:

select k.*
from KB_OBJECT_IDENTIFIERS k
where k.type in ('ISSN', 'ISBN') and
      exists (select 1
              from KB_OBJECT_IDENTIFIERS k2
              where k2.object_id = k.object_id and
                    k2.type in ('ISSN', 'ISBN') and
                    k2.type <> k.type
             );

答案 2 :(得分:0)

计数中的DISTINCT

HAVING count(DISTINCT K.`TYPE`) = 2