子查询 Postgres:两个不直接相关的表

Subquery Postgres: two tables not directly related

盘子

plate_id date product_id
1 01-12-2020 101
2 01-12-2020 202
3 02-12-2020 101
4 02-12-2020 202
5 02-12-2020 303

制作

order_id date product_id cost
1001 01-12-2020 101 10.95
1002 01-12-2020 202 19.00
1003 02-12-2020 101 11.50
1004 02-12-2020 202 20.05
1005 02-12-2020 303 17.00

我需要得到的查询结果是:

plate_id cost
4 20.05

它们与pk和fk无关,

每个产品的生产成本可以超过一个。

我想我需要创建一些子查询,以便始终考虑两列:日期和 product_id

不幸的是,下面的查询给出了一个错误

SELECT pl.plate_id, pr.cost
FROM plates pl
JOIN (select * from production pr where pr.date=pl.date and pr.product_id=pl.product_id)
WHERE pl.product_id = 4;

您似乎想加入 product_iddate:

select pl.plate_id, pr.cost
from plates pl
inner join production pr using (product_id, date)
where pl.plate_id = 4