涉及三张表的Postgresql查询

标签 postgresql

我有三个表,说:

(1) 名称:组

列:gid,组名

(2) 姓名:简介

列:profileid,profname

(3) 名称:GroupsProfiles

列:gid、profileid - 对应于前面表格中的列

现在,假设我有一个 profileid 数组,我想构建一个查询,在 GroupsProfiles 中找到相应的 gid,然后从中找到 Groups 中的相应组名。

我一直在尝试连接和其他东西,但没有得到我想要的。有什么想法吗?

最佳答案

使用连接(将 your_profile_id 替换为您关心的个人资料 ID):

SELECT p.profileid
     , g.gid
     , g.GroupName
  FROM Groups g
     , Profiles p
     , GroupsProfiles gp
 WHERE g.gid = gp.gid
   AND p.profileid = gp.profileid
   AND p.profileid = your_profile_id

您将为每个配置文件 ID 运行此查询。如果您想获取所有个人资料或部分个人资料的信息,您可以删除 your_profile_id 上的条件,或者如果您知道自己想要哪些,也可以使用 IN 子句,例如

SELECT g.gid
     , g.GroupName
  FROM Groups g
     , Profiles p
     , GroupsProfiles gp
 WHERE g.gid = gp.gid
   AND p.profileid = gp.profileid
   AND p.profileid IN (profile_id_1, profile_id_2, ... ,profile_id_N)

关于涉及三张表的Postgresql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3318434/

相关文章:

ruby-on-rails - 对于多个 sidekiq 进程,sidekiq 和 postgres 的 activerecord 连接池大小是否合适?

linux - 如何提高 Postgresql 'truncate' 性能?

java - date_trunc org.postgresql.util.PSQLException : ERROR: syntax error at or near "$1"

postgresql - 在 Navicat 结果窗口中查看列中的整个文本

sql-server - 如何在postgresql中声明局部变量?

postgresql - INSERT ... ON CONFLICT (id) DO UPDATE... 语法如何与序列 ID 一起使用?

python - 是否可以在 postgresql 数据库中插入 python 元组

Postgresql - PSQL 编码问题

sql - 建议锁定或 NOWAIT 以避免等待锁定的行?

python - 如何在Python中打印查询结果,包括列名