在Postgresql中基于“标签”查找实体

3zwtqj6y  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(150)

假设我在Postgresql 12中有两个表,其中一个存储project的基本数据,每个project s可以有任意一组label s:

CREATE TABLE projects (
  id SERIAL,
  title TEXT
);
CREATE TABLE labels (
  id SERIAL,
  projects_id INT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
  key VARCHAR(127) NOT NULL,
  value TEXT NOT NULL,
  UNIQUE (projects_id, key)
);

字符串
现在我想创建一个查询,它返回所有projects,这些projects匹配labels中的all多个键/值组合。我想使用“任意”数量(比如至少5个)的标签匹配。
选择projects与一个标签完全匹配很简单:

SELECT 
  p.id, p.title 
FROM projects p 
JOIN labels l ON l.projects_id = p.id 
WHERE l.key = 'k1' AND l.value = 'v1';


只是使用

SELECT p.id, p.title
FROM projects p
JOIN labels l ON l.projects_id = p.id 
WHERE 
  l.key = 'k1' AND l.value = 'v1' AND 
  l.key = 'k2' AND l.value = 'v2';


它不起作用,我知道为什么。
什么是只使用SQL的最佳方法?

b4qexyjb

b4qexyjb1#

您可以:

select p.*
from projects p
join (
  select projects_id 
  from labels
  where (key, value) in (
    ('k1', 'v1'), -- The list of labels to look for
    ('k2', 'v2'),
    ('k3', 'v3'),
    ('k4', 'v4'),
    ('k5', 'v5')
  )
  having count(*) = 5 -- We want full count of them
  group by projects_id
) x on x.projects_id = p.id

字符串

相关问题