2014-11-08 28 views
6
sahip

Ben Scala ve Slick için yeniyim. Slick ile sorgu oluşturmamın yolunu anlamaya çalışıyorum. Şimdiye kadar basit sorgulamalar yapabildim ama SELECTs, JOINs, GROUP BYs vb. Ile birleştirmek için mücadele ettim.Birden çok birleştirme ile kaygan sorgu, grup ve

Sanal kitap raflarımı (PHP ile harcayarak) Scala'ya dönüştürmenin tam ortasındayım. Oyna ve kaygan. Benim kitap rafında en az 3 kitap var kimden

listesi bu yazarlar (5'e sınırı):

Bu

istiyorum gerçekleştirmek sorgusu olur.
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 

Görünüşe aşağıdaki kodla ben oluşturmak başarmış gerekli katılır:

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

Ben SEÇ, GroupBy uygulamak ve yukarıdaki koduna HAVING nasıl kayboldum.

+0

Lütfen (kaygan docs türetilmiş) http://slick.typesafe.com/doc/2.1.0- M2/from-sql-to-slick.html # sahip) slick belgeler sayfası. –

+0

Veya SQL sorgusunu saklayabilir ve sonucu ayrıştırmak için Anorm'a bakabilirsiniz. – cchantep

cevap

11

Sadece birisi aradığı durumda (, [bu] bir göz

(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) 
İlgili konular