繁体   English   中英

select 多类所有记录

[英]select all records with multiple category

我试图弄清楚如何 select 与列表中的所有类别相关联的所有记录。

例如采取这个数据库设置:

create table blog (
  id integer PRIMARY KEY,
  url varchar(100)
  );
  
create table blog_category (
  id integer PRIMARY KEY,
  name varchar(50)
  );

create table blog_to_blog_category (
  blog_id integer,
  blog_category_id integer
  );
  
  insert into blog values 
    (1, 'google.com'),
    (2, 'pets.com'),
    (3, 'petsearch.com');
    
insert into blog_category values
  (1, 'search'),
  (2, 'pets'),
  (3, 'misc');
  
insert into blog_to_blog_category values
  (1,1),
  (2,2),
  (3,1),
  (3,2),
   (3,3);

我可以像这样查询主表:

select b.*, string_agg(bc.name, ', ') from blog b
join blog_to_blog_category btbc on b.id = btbc.blog_id 
join blog_category bc on btbc.blog_category_id = bc.id
where b.url like '%.com'
group by b.id

但是,假设我只想返回同时具有 1 类和 2 类的博客,我该怎么做?

这将只返回petsearch.com域,因为它只是同时具有这两个类别的记录。

这是一种方法:

select * from blog where id in ( 
select blog_id
from blog_to_blog_category bbc
where blog_category_id in (1, 2)
group by blog_id
having count(distinct blog_category_id) = 2
)

这里是 go:

添加了一个检查来计算 blog_category id(HAVING 子句),如果它是 2,那么它应该是 1 或 2(IN 子句),

select b.*, string_agg(bc.name, ', ') from blog b
join blog_to_blog_category btbc on b.id = btbc.blog_id 
join blog_category bc on btbc.blog_category_id = bc.id
where b.url like '%.com' and bc.id in (1,2)
group by b.id
having count(distinct bc.id ) =2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM