如何在PostgreSQL中提取相关值?

如何在PostgreSQL中提取相关值?,sql,postgresql,Sql,Postgresql,这是我的问题 我有两个表,像user和customer。用户可能与某些客户相关 例如,我有一个用户与两个客户相关,另一个用户与三个客户相关,以此类推 这是我创建表和插入值的代码 create table tbl_user ( id int, username varchar(100), relatedcustom_id int ) create table tbl_custom ( id int, name varchar(100) ) insert into tbl_cust

这是我的问题

我有两个表,像user和customer。用户可能与某些客户相关

例如,我有一个用户与两个客户相关,另一个用户与三个客户相关,以此类推

这是我创建表和插入值的代码

create table tbl_user
(
 id int,
 username varchar(100),
 relatedcustom_id int
)

 create table tbl_custom
(
 id int,
 name varchar(100)
)

 insert into tbl_custom values(1,'john'),
 (2,'adam'),
 (3,'steve'),
 (4,'marliyn'),
 (5,'coco'),
 (6,'George');

 insert into tbl_user values (1,'cst_moose',1),
 (1,'cst_moose',2),
 (2,'cst_moose',3),
 (3,'cst_kevin',2),
 (4,'cst_kevin',5),
 (5,'cst_donald',1),
 (6,'cst_donald',2),
 (7,'cst_donald',4),
 (8,'cst_henry',1),
 (9,'cst_henry',6),
 (10,'cst_michel',1),
 (11,'cst_michel',2);
我想提取与id为1和2的客户相关的用户名

这是我的选择代码

  select username from tbl_user where exists (select 1 from tbl_custom 
  where 
  id in(1,2))
  except
  select username from tbl_user where exists (select 1 from tbl_custom 
  where 
  id not in(1,2))
但这个查询并没有证明什么

另一个选择代码

select username from tbl_user where relatedcustom_id in (1,2)
except
select username from tbl_user where relatedcustom_id not in (1,2)
这个查询显示如下

  username
  --------
  cst_michel
我要做的是使用以下字段从中选择

   username
  --------
  cst_michel
  cst_moose
  cst_donald
我想提取与id为1和2的客户相关的用户名

您可以使用聚合并具有:


可能的解决方案之一是使用阵列:

select username
from tbl_user
where relatedcustom_id in (1,2) -- to filter out unrelated data
group by username
having array[1,2] <@ array_agg(relatedcustom_id);
-- or '{1,2}' <@ array_agg(relatedcustom_id);

您的用户需要相关的子查询。您的所有用户都有相同的ID-1我修复了相同的ID问题@Svetlin zarev谢谢您的快速回答。但是,我需要将自定义id字段作为列表发送,我没有如上所示进行分离。此外,该查询仅返回cst_michel@MustafaBYKSY . . . 那不是你问的问题。对不起,我的英语@Gordonlinoff非常感谢,它正在工作,我们为什么用它,我不明白。你能解释一下吗@Abelisto@MustafaBYKSY看看文档:它不是@but
select username
from tbl_user
where relatedcustom_id in (1,2) -- to filter out unrelated data
group by username
having array[1,2] <@ array_agg(relatedcustom_id);
-- or '{1,2}' <@ array_agg(relatedcustom_id);