首页 文章

具有多个连接,分组和拥有的光滑查询

提问于
浏览
7

我是Scala和Slick的新手 . 我试图理解我应该用Slick创建查询的方式 . 到目前为止,我已经能够创建简单的查询,但很难合并SELECT,JOIN,GROUP BY等 .

我正在将我的虚拟书架(使用PHP的meade)转换为Scala,Play和Slick .

这是我想要完成的查询:

列出那些作者(限制为5),我的书架上至少有3本书 .

SELECT
    a.id,
    a.firstname,
    a.lastname,
    count(b.id) AS amount
FROM
    book b LEFT JOIN book_author ba ON b.id = ba.book_id
    LEFT JOIN author a ON a.id = ba.author_id
GROUP BY 
    a.id
HAVING 
    amount >= 3
ORDER BY 
    amount DESC
LIMIT 
    5

显然,我使用以下代码创建了所需的连接:

(for(b <- books; a <- authors; ba <- bookAuthors; if b.id === ba.bookId && a.id === ba.authorId) yield (a.id, b.id)).run

我迷失了如何将SELECT,GROUPBY和HAVING应用于上面的代码 .

1 回答

  • 14

    以防万一有人正在寻找它(源自光滑的文档)

    (for {
        //joins
        book <- books
        bookAuthor <- bookAuthors if book.id === bookAuthor.bookId
        author <- authors if bookAuthor.authorId === author.id
    } yield (author, book.id)).groupBy({
        //group by author
        case (author, bookId) => author
    }).map({
        //count bookIds
        case (author, authorBookIds) => (author, authorBookIds.map(_._2).count)
        //having count bookIds >= 3
    }).filter(_._2 >= 3)
    // order by count desc
    .sortBy(_._2.desc)
    // limit 5
    .take(5)
    

相关问题