选择某一列中只有一个值的行

问题描述

我有一个表中的项目列表,我只想选择其中的一些: 这是我的桌子:

CREATE TABLE conexiones(
    idCon int not null,idType int not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

这里是 conexiones 项目:

INSERT INTO conexiones (idCon,idType) VALUES
(1,1),(2,(3,(4,(5,(6,2),2);

我得到的是这组结果:

idCon idType
1 1
2 1
3 1
4 1
5 1
6 1
2 2
3 2
4 2

我需要的:

显示所有不共享相同 idCon,但具有不同 idType 的项目。

预期结果示例 1:

显示 idType 1 的项目,但删除 idType 为 1 且与 idType 2 共享 idCon 的项目,因此预期结果为:

idCon idType
1 1
5 1
6 1

预期结果示例2:

显示 idType 2 的项目,但消除任何 idType 为 2 且与 idType 1 共享 idCon 的项目,因此预期结果是:

idCon idType
没有结果

我应该如何实现这一目标?

解决方法

您的示例 1 是不是错了? 不应该是这样的:

idCon idType
1 1
5 1
6 1

示例 1:

SELECT idCon,idType
FROM conexiones
WHERE idCon NOT IN (SELECT idCon FROM conexiones WHERE idType=2)
AND idType=1;

示例 2:

SELECT idCon,idType
FROM conexiones
WHERE idCon NOT IN (SELECT idCon FROM conexiones WHERE idType=1)
AND idType=2;
,

您可以这样做。

select * from conexiones
 where idType = 1 -- Show only items with idType 1
    and idCon not in ( -- eliminating the item that has idType of 1 and does share an idCon with idType 2
        select idCon from conexiones where idType=2
    );
    
select * from conexiones
 where idType = 2
    and idCon not in (select idCon from conexiones where idType=1);

工作演示 -> https://www.db-fiddle.com/f/sYajoTcAbEPVdVxSNYfSJ2/0

,

以下可能的解决方案:

select distinct idCon,min(idType) idType
from conexiones group by idCon
having count(distinct idType) = 1

SQL fiddle

使用上面的单个查询,我们可以选择所有具有单个 idType(1 和 2)的项目