SQL子查询问题,“错误:对FROM子句条目的无效引用......”

时间:2011-09-06 16:39:00

标签: sql postgresql subquery

遇到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进行此操作吗?

2 个答案:

答案 0 :(得分:2)

试试这个

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

答案 1 :(得分:0)

您需要横向连接:

HKAnchoredObjectQuery