Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8900

knexでdistinct onする方法

$
0
0

特定のカラムだけdistinctしてーーー!
そしてdistinctしたカラム以外も取得してーーーー!

って時、極稀にありますよね。
RDBに多少でも触れる人生なら一生に3回くらいは遭遇するはずです。

エンジニア歴10年超えにしてやっと実運用ProductでPostgresデビューした私にも、人生で3回遭遇するうちの第一回目が来ました。

knexのドキュメント見てもですね。
「distinct on」サポートしてないんですよ。

http://knexjs.org/

distinct on なにそれ?おいしいの?くらいの勢いでカレーにスルーされてるんです。
Postgresの方言らしいので仕方ないのかな。。

もうこういったRDB固有の方言は、raw使うしか無いようですロー

knexでdistinct on するには"raw"を使う

knex.select(knex.raw('DISTINCT ON (target_colum) target_colum1, other_colum2, other_colum2)

こうすると、target_columでdistinctしつつ、other_colum1とother_colum2も取得できます。

orderも組み合わせる

knex.select(knex.raw('DISTINCT ON (target_colum) target_colum1, other_colum2, other_colum2).orderBy([target_colum, {target_colum1: 'desc'}])

orderByの1つ目は必ずdistinct onで指定したやつに。

2つ目に指定したカラムでソートして一番最初に出る行が残されて取得できるよ


Viewing all articles
Browse latest Browse all 8900

Trending Articles