我有一个sql表,为了这篇文章的目的,我们会说它有2列,名称和值。有多个名称记录具有不同的值条目。在某些情况下,如果名称存在值,则还必须存在一组其他值。我试图确定哪种情况不会发生。例如,如果存在“组合”值,则必须存在值“1”和“2”才能处于正确状态。我正在尝试像这样的查询:
Select Name
From Table
Where Value = "combo"
And Value Not Exists
(
Select Name
From Table
Where Value IN ("1", "2")
)
有更好的方法吗?
答案 0 :(得分:0)
select name
from table
where value in ('combo', '1', '2')
group by name
having count(distinct value) = 3
或
select name
from table
group by name
having sum(case when value = 'combo' then 1 else 0 end) = 1
and sum(case when value = 1 then 1 else 0 end) = 1
and sum(case when value = 2 then 1 else 0 end) = 1
答案 1 :(得分:0)
如果表格中存在combo
,则会返回1
,但值2
或select name
from table
where value = "combo"
and (
select count(distinct value)
from table
where value IN ("1", "2")
) < 2
或两者都不会。
{{1}}
答案 2 :(得分:0)
您对问题的一种解释是:
`forall name: exists (value = combo) => exists (value in (1,2))`
A => B
与~A or B
相同,并转换为SQL:
select distinct name from T T1
where not exists (
select 1 from T T2
where T2.name = T1.name
and T2.value = 'combo'
)
or exists (
select 1 from T T3
where T3.name = T1.name
and T3.value in (1,2)
);
这是你的意思吗?