LoginSignup
0
0

More than 3 years have passed since last update.

knexでdistinct onする方法

Last updated at Posted at 2020-04-27

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

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

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

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

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, {column: 'target_colum1', order: 'desc'}])

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

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0