LoginSignup
0
0

More than 5 years have passed since last update.

ActiveRecordでUNIONしない

Posted at

そもそもUNIONが必要なDB設計をしないようにしましょう。
既存を触るなど必要に迫られてもUNIONを頑張るより大事な事があると思います。
ですので、私はstatementでお茶を濁しました。

キーも異なるテーブルのupdated_atをdistinctする必要があったので
※sample1,2にはrelation_idに複数レコードが存在してる想定です。

query = "SELECT distinct SB.updated_at \
         FROM \
         (SELECT updated_at FROM sample1 WHERE relation_id = ? \
         UNION \
         SELECT updated_at FROM sample2 WHERE relation_id = ?) SB \
         ORDER BY updated_at DESC"

buffer = []
statement = ActiveRecord::Base.connection.raw_connection.prepare(query)
statement.execute(1, 10).each {|result| buffer.push result}
statement.close

SQLを頑張らないDB設計を心がけたいですね。

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