SQL 子查询问题,“错误:对 FROM 子句条目的引用无效...”
使用 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 来做到这一点吗?
Having trouble with SQL (currently using postgresql)
I have this query as I need to compare the most recent item and the second most recent item:
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
This produces a few errors:
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.
Is there any reason I can't access p1 from that subselect, is it a existence issue, as in, p1's data isn't available yet? Is there another way to do this with a JOIN?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这个
根据作者评论
更新如果您需要最近第二个条目中的多个列,您可以尝试以下代码片段
Try this one
UPDATE according to authors comment
If you need more than one column from second recent entry, you can try following snippet
您需要横向连接:
You need a LATERAL JOIN: