【发布时间】:2016-05-21 23:38:21
【问题描述】:
我正在尝试加入对帖子记录的最新评论,如下所示:
comment = from c in Comment, order_by: [desc: c.inserted_at], limit: 1
post = Repo.all(
from p in Post,
where: p.id == 123,
join: c in subquery(comment), on: c.post_id == p.id,
select: [p.title, c.body],
limit: 1
)
生成此 SQL:
SELECT p0."title",
c1."body"
FROM "posts" AS p0
INNER JOIN (SELECT p0."id",
p0."body",
p0."inserted_at",
p0."updated_at"
FROM "comments" AS p0
ORDER BY p0."inserted_at" DESC
LIMIT 1) AS c1
ON c1."post_id" = p0."id"
WHERE ( p0."id" = 123 )
LIMIT 1
它只返回nil。如果我删除 on: c.post_id == p.id 它会返回数据,但显然它会返回所有帖子的最新评论,而不是相关帖子。
我做错了什么?解决方法是使用LATERAL 连接子查询,但我不知道是否可以将p 引用传递给subquery。
谢谢!
【问题讨论】:
标签: sql postgresql elixir phoenix-framework ecto