sql - JOIN psql 中的三个表(SQL 查询)

标签 sql postgresql

我有一个这样的表:

UsersDevices: user_id, device_id
registration_posusercompany: company_id, user_id
registation_companyprofile: company_id, company_name

我知道UsersDevices中的device_id,我现在想知道设备所属的company_name。为此,伪代码如下所示:

--> Get user_id from UsersDevices where device_id = (I know this device_id)
--> Get company_id with that user_id from registration_posusercompany
--> Get company_name with that company_id

我正在编写子查询来执行此操作,但与 JOIN 相比,子查询确实非常慢。如何使用 JOIN 实现此目的。谢谢

最佳答案

select rc.company_name 
from UsersDevices as u 
   join registration_posusercompany as rp on rp.user_id = u.user_id 
   join registation_companyprofile as rc on rc.company_id = rp.company_id 
where u.device_id = yourvalue

关于sql - JOIN psql 中的三个表(SQL 查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23110454/

相关文章:

c# - 如何根据数据库中的数字字段填充动态下拉列表?

sql - 同时在多个列上选择不同的,并在 PostgreSQL 中保留一列

mysql - 如何在 Sql 触发器中获取当前已删除行的值并使用已删除的行数据更新另一个表

mysql - 使用mysql在一个查询中查询计数,总和,带条件

sql - 用最后的结果填表

database - 如何测量数据库表中数据的大小?

sql - 在 postgres json 数组中查找单个元素

mysql - 根据连接表中的最新行选择 MySQL 结果

postgresql - Postgres : dump partial tables between databases while maintaining sequences

ruby-on-rails - 你如何访问你的 heroku 数据库(特别是 postgres)?