如何选择具有精确外键的主键与给定的值列表匹配?

Dev*_*v X 9 mysql sql sql-server oracle

例如:

pk_ref    fk
======    ===
1         a
1         b
1         c
2         a
2         b
2         d
Run Code Online (Sandbox Code Playgroud)

如何进行"伪"查询之类的查询:

select distinc pk_ref
where fk in all('a', 'c');
Run Code Online (Sandbox Code Playgroud)

返回查询结果必须匹配列表中外键的所有给定值.

结果应该是:

1
Run Code Online (Sandbox Code Playgroud)

而以下选择不得返回任何记录.

select distinc pk_ref
where fk in all('a', 'c', 'd');
Run Code Online (Sandbox Code Playgroud)

我怎么做?

Pரத*_*ீப் 6

试试这个

select pk_ref 
from yourtable 
group by pk_ref 
having count(case when fk = 'a',  then 1 end) >= 1 
and count(case when fk = 'c' then 1 end) >= 1
Run Code Online (Sandbox Code Playgroud)

动态地做.(考虑到你使用的是SQL SERVER)

创建拆分字符串函数并将输入作为逗号分隔值传递

Declare @input varchar(8000)= 'a,c',@cnt int 

set @cnt = len(@input)-len(replace(@input,',','')) + 1

select pk_ref 
from yourtable 
Where fk in (select split_values from udf_splitstring(@input , ','))
group by pk_ref 
having count(Distinct fk) >= @cnt 
Run Code Online (Sandbox Code Playgroud)

您可以从以下链接创建拆分字符串函数

https://sqlperformance.com/2012/07/t-sql-queries/split-strings