来自两个不同 table 的 Postgres 查询

Postgres query from two different table

您好,我有一些用于获取单一结果的查询。我怎么能只用一个查询就做到这一点?

先问一下

SELECT "userId" FROM "Devices" WHERE "deviceNumber" = '0001563055080020'

然后保存UserId并询问另一个table

SELECT "email" FROM "Users" WHERE "id" = '1'

有什么想法吗?

这称为连接

这是一种语法

select email
from users u, devices d
where d.userid = u.id

嵌套查询

SELECT "email" 
FROM "Users" 
WHERE "id" IN (
    SELECT "userId" 
    FROM "Devices" 
    WHERE "deviceNumber" = '0001563055080020')

内连接

select u.email
from users u, devices d
where d.userid = u.id
and d.deviceNumber = '0001563055080020'

我建议使用新的连接语法。我认为它更干净,更易于阅读。可以立即看到有一个内部连接。此外,where 子句可以仅用于过滤。

select u.*
from users u
inner join devices d on u.id=d.user_id
where d.device_number='0001234';