在psql(SQL查询)中连接三个表
我有一张这样的桌子:在psql(SQL查询)中连接三个表,sql,postgresql,Sql,Postgresql,我有一张这样的桌子: UsersDevices: user_id, device_id registration_posusercompany: company_id, user_id registation_companyprofile: company_id, company_name --> Get user_id from UsersDevices where device_id = (I know this device_id) --> Get company_id wi
UsersDevices: user_id, device_id
registration_posusercompany: company_id, user_id
registation_companyprofile: company_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
我知道UsersDevices
中的device\u id
,现在我想知道该设备所属的公司名称。因此,psuedo代码如下所示:
UsersDevices: user_id, device_id
registration_posusercompany: company_id, user_id
registation_companyprofile: company_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实现这一点。谢谢你我想你是说PostgreSQL吗?是的,先生。我的意思是PostgreSQL。我应该在哪里应用,where device_id=something
?另外,如果您只想从UsersDevices表中选择列,那么您可以执行“select u.*from UsersDevices as u…..”我只想从registration\u companyprofile
中选择列。我只想要公司名称
谢谢。很好用。感谢您的输入@JosephB
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