PostgreSQL JOIN 来自 3 个表的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15799556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:07:53  来源:igfitidea点击:

PostgreSQL JOIN data from 3 tables

postgresql

提问by John Cleary

I'm new to PostgreSQL and trying to get a query written. I'm pretty sure it's easy for someone who knows what they are doing - I just don't! :)

我是 PostgreSQL 的新手,正在尝试编写查询。我很确定这对于知道自己在做什么的人来说很容易——我就是不知道!:)

Basically I have three tables. In the first, I store details about patients. In the second, I store a reference to each image of them. In the third, I store the link to the file path for the image. I didn't design the database, so I'm not sure why the image files table is separated, but it is.

基本上我有三张桌子。首先,我存储有关患者的详细信息。在第二个中,我存储对它们的每个图像的引用。在第三个中,我存储指向图像文件路径的链接。我没有设计数据库,所以我不确定为什么图像文件表是分开的,但确实如此。

What I want to be able to do is select data from the first table, joining in data from a second then third table so I end up with the name & file path in the result.

我想要做的是从第一个表中选择数据,加入第二个然后第三个表中的数据,这样我最终会在结果中得到名称和文件路径。

So the basic structure is:

所以基本结构是:

Table 1:
person_id | name

Table 2:
person_id | image_id

Table 3:
image_id | `path filename`

What I want to do is in one query, grab the person's 'name' and the image 'path filename'.

我想要做的是在一个查询中,获取此人的“姓名”和图像“路径文件名”。

I'm happy with a "template" style answer with the join I need. I don't need it to be written in actual code. (i.e. I'm thinking you can just write me an answer that says SELECT table1.name, table3.pathfilename FROM JOIN ... etc...).

我对带有我需要的连接的“模板”样式的答案感到满意。我不需要用实际代码编写它。(即我想你可以给我写一个答案,上面写着SELECT table1.name, table3.pathfilename FROM JOIN ... etc...)。

回答by ozczecho

Something like:

就像是:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

回答by Daniel Frey

Maybe the following is what you are looking for:

也许以下是您正在寻找的内容:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';