如何根据键值对查询table,其中键是一个整数,值是一个整数列表

how to query table based on keyvaluepair where key is an integer and value is a list of integers

所以,我有一个 table,它有 3 个东西:主键、table_id、foreignkey_id 和 doctor_id。 - table_id 指的是 table 具有一定的数字。 - foreignkey_id 指的是 table 中的主键。 - doctor_id 指的是 doctor table 中的主键 现在,用户将 select 他想使用哪些 table 以及他想要 table 中的哪些项目。我需要所有匹配组合的 doctor_id。

CREATE TABLE tConfidentiality(
    confidentiality_id serial primary key,
    table_id integer not null,
    doctor_id integer not null,
    foreignkey_id integer not null,
    constraint un_confidentiality unique(table_id, doctor_id, foreignkey_id)
);
INSERT INTO tConfidentiality(table_id, doctor_id, foreignkey_id) values(10, 100, 1000);
INSERT INTO tConfidentiality(table_id, doctor_id, foreignkey_id) values(10, 100, 2800);
INSERT INTO tConfidentiality(table_id, doctor_id, foreignkey_id) values(40, 100, 2000);
INSERT INTO tConfidentiality(table_id, doctor_id, foreignkey_id) values(80, 110, 2500);
INSERT INTO tConfidentiality(table_id, doctor_id, foreignkey_id) values(90, 120, 2800);

查询:值必须参数化

所有 doctor_id in table 10 with foreignkey_id 1000 & 2800 and table 40 with foreignkey_id 2000

预期结果:100

不要指望你写完整的东西,只要给我指出正确的方向,我就会从那里开始。

根据您的示例,您可以在相同的 table

之间使用连接
select  doctor_id 
from  tConfidentiality t1
inner join tConfidentiality t2 on t1.doctor_id = t2.doctor_id
where t1.table_id = 10  AND t1.foreignkey_id IN (1000,2800  )
AND t2.table_id = 40 and t2.foreignkey_id = 2000

您需要收集每个 table_id 的外键 ID,然后检查是否至少包含您要查找的外键 ID。在 Postgres 中,这可以通过将它们聚合到一个数组中来完成:

select distinct doctor_id
from tConfidentiality
group by doctor_id, table_id
having table_id = 10 and array_agg(distinct foreignkey_id) @> array[1000,2800]
    or table_id = 40 and array_agg(distinct foreignkey_id) @> array[2000];

在线示例:https://rextester.com/NHE4869