1

単純な HABTM リレーションシップ Books <-> Authors があり、タイトルと著者の名前で本を取得したいと考えています。

Book.joins(:authors)
    .where("books.title ILIKE 'roman%' OR authors.name ILIKE 'pushkin%'")
    .order("books.id DESC").limit(20).group("books.id")

それは完璧に機能します。

しかし、著者名でさらに並べ替えたい場合は、多くの著者がいる本の重複した行を取得しました:

Book.joins(:authors)
    .where("books.title ILIKE 'roman%' OR authors.name ILIKE 'pushkin%'")
     .order("books.id DESC, authors.id DESC").limit(20).group("books.id, authors.id")

私は次のようなものを得ました:

id  | title  | ...
123 | Roman1 |   // this book has only 1 author
55  | roman2 |  
55  | roman2 |   // this one hase 2 authors
177 | Roman5 | ... 
etc.

id これらの行を SQL クエリ (ところで、Postgres 9.1) でマージするにはどうすればよいですか?

4

1 に答える 1

0

問題は注文部分ではなく、部分ごとのグループ化です。著者を含めると、それはあなたが本と著者の間にも違いをもたらすことを意味します。

author.idを省略し、SQLではなくコードからリストを並べ替えることをお勧めします。

于 2012-07-05T18:08:03.993 に答える