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

时间:2014-11-08 10:31:57

标签: mysql scala playframework slick

我是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 个答案:

答案 0 :(得分:15)

以防万一有人在寻找它(从光滑的文档中获取)

(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)