2014-11-08 80 views
6

我是新來的斯卡拉和油滑。我試圖理解我應該用Slick創建查詢的方式。我到目前爲止,我已經能夠創建簡單的查詢,但努力與結合SELECTs,JOINs,GROUP BYs等有多個連接的有問題的查詢,分組和有

我正在轉換我的虛擬書架(meade與PHP)到斯卡拉,玩和光滑。

這是我想要完成的查詢:

名單的作者(限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上面的代碼。

+0

請看看[這裏](http://slick.typesafe.com/doc/2.1.0- M2/from-sql-to-slick.html#having)光滑的文檔頁面。 – 2014-11-09 09:45:08

+0

或者您可以保留SQL查詢並查看Anorm來解析結果。 – cchantep 2014-11-09 11:38:15

回答

11

萬一有人找它(從光滑文檔導出)

(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) 
相關問題