遇到SQL问题(当前使用的是postgresql)
我有这个查询,因为我需要比较最近的项目和第二个最近的项目:
SELECT p1.*, p2.price_cents FROM "prices" p1 INNER JOIN ( SELECT price_cents, game_id from prices as p WHERE p.game_id = p1.game_id ORDER BY p.created_at DESC LIMIT 1 OFFSET 1 ) p2 ON p2.game_id = p1.game_id
这会产生一些错误:
ERROR: invalid reference to FROM-clause entry for table "p1" LINE 1: ...AND p.game_id = p1.game_id... ^ HINT: There is an entry for table "p1", but it cannot be referenced from this part of the query.
有什么原因我无法从该子选择访问p1,是否存在问题,例如p1的数据尚不可用?还有另一种方法可以用JOIN做到这一点吗?
试试这个
SELECT p1.*, ( SELECT price_cents FROM "prices" p WHERE p1.game_id = p.game_id ORDER BY p.created_at DESC LIMIT 1 OFFSET 1 ) as price_cents FROM "prices" p1
*根据作者评论 *更新
如果您需要最近的第二个条目中的一列以上,则可以尝试按照以下代码段进行操作
SELECT * FROM ( SELECT p.*, ( SELECT id FROM "prices" WHERE p.game_id = game_id ORDER BY created_at DESC LIMIT 1 OFFSET 1 ) AS second_id FROM "prices" p ) p1 INNER JOIN "prices" p2 ON p1.second_id = p2.id