如何从具有 SQL 的另一列中仅具有一个特定值的列中提取值?
How to extract values from column that have only one specific value in other column with SQL?
我有一个table:
id value type
a1 146 out
a1 198 upload
bb 11 upload
q5 16 upload
q5 88 upload
ff 19 delete
我想提取只有类型等于“上传”的唯一 ID。所以想要的必须是:
bb
q5
怎么做?
您可以尝试以下查询 -
SELECT DISTINCT id
FROM TABLE
WHERE type = 'upload'
AND id NOT IN (SELECT ID
FROM TABLE
WHERE type <> 'upload')
第一个也是最常见的方法是使用“不存在”
select distinct td.id
from test_data td
where td.type = 'upload'
and not exists (select 1
from test_data td2
where td2.id = td.id
and td2.type <> 'upload');
但我喜欢在这种情况下使用左连接,因为它有助于避免子查询
select distinct td1.id
from test_data td1
left join test_data td2
on td1.id = td2.id
and td2.type <> 'upload'
where td1.type = 'upload'
and td2.id is null
第三种方法会更棘手,但也放在这里
首先,select那些只有一种类型(having从句)
然后,自加入 id 仅过滤那些具有 type = 'upload'
的人
select td.id
from test_data td
join test_data td2
on td.id = td2.id
and td2.type = 'upload'
group by td.id
having count(distinct td.type) = 1
只需选择执行速度更快的那个
我有一个table:
id value type
a1 146 out
a1 198 upload
bb 11 upload
q5 16 upload
q5 88 upload
ff 19 delete
我想提取只有类型等于“上传”的唯一 ID。所以想要的必须是:
bb
q5
怎么做?
您可以尝试以下查询 -
SELECT DISTINCT id
FROM TABLE
WHERE type = 'upload'
AND id NOT IN (SELECT ID
FROM TABLE
WHERE type <> 'upload')
第一个也是最常见的方法是使用“不存在”
select distinct td.id
from test_data td
where td.type = 'upload'
and not exists (select 1
from test_data td2
where td2.id = td.id
and td2.type <> 'upload');
但我喜欢在这种情况下使用左连接,因为它有助于避免子查询
select distinct td1.id
from test_data td1
left join test_data td2
on td1.id = td2.id
and td2.type <> 'upload'
where td1.type = 'upload'
and td2.id is null
第三种方法会更棘手,但也放在这里
首先,select那些只有一种类型(having从句) 然后,自加入 id 仅过滤那些具有 type = 'upload'
的人select td.id
from test_data td
join test_data td2
on td.id = td2.id
and td2.type = 'upload'
group by td.id
having count(distinct td.type) = 1
只需选择执行速度更快的那个