我的项目有下一个表格:帖子、用户、评论。发表一对多评论,发表多对一用户。我想获取所有带有评论和用户的帖子,并按评论计数排序。第一个问题是不正确的限制,但我通过子查询解决了这个问题。但是如何按计数查询对帖子进行排序?
这是我在 scalikeJDBC 中的 DSL 操作:
val x = SubQuery.syntax("x").include(v, p, u)
DB readOnly { implicit session =>
withSQL {
select.all(p,u,v)
.from(Post as p)
.leftJoin(Vote as v)
.on(p.postId, v.postId)
.join(User as u)
.on(p.userId, u.userId)
.join{
select(p.result.*,count(v.voteId))
.from(Post as p)
.leftJoin(Vote as v)
.on(p.postId, v.postId)
.join(User as u)
.on(p.userId, u.userId)
.groupBy(p.postId)
.as(x)
}.on(x(p).postId, p.postId)
}
.one(Post(p.resultName, u.resultName))
.toMany(
rs => Vote.opt(v)(rs),
).map{
(p:Post,v:Seq[Vote])=> {
p.copy(votes = v)
}
}.list.apply
}
我知道如何在 SQL 中做到这一点:
SELECT * FROM blog.POSTS p LEFT JOIN BLOG.POST_VOTES pv ON p.POST_ID = pv.POST_ID JOIN (SELECT p2.POST_ID as id, COUNT(pv2.VOTE_ID) "count" FROM BLOG.POSTS p2 LEFT JOIN BLOG.POST_VOTES pv2 ON p2.POST_ID = pv2.POST_ID GROUP BY p2.POST_ID) r ON p.POST_ID = r.id ORDER BY r."count";
我如何count(v.voteId)
在 DSL 中订购?.orderBy(x(count(v.voteId)))
不工作