S
S
Sergey Ozeransky2016-02-11 15:05:00
Ruby on Rails
Sergey Ozeransky, 2016-02-11 15:05:00

Rails, complex query - select in select, how?

Good afternoon.
I'm stuck on the implementation in rails of a complex request, like:

SELECT *
FROM
  (SELECT
     directory_records.id AS did,
     organisations.title  AS org
   FROM "directory_records"
     LEFT OUTER JOIN organisations
       ON organisations.id = directory_records.organisation_id
     LEFT OUTER JOIN directory_values
       ON directory_values.directory_record_id = directory_records.id
   WHERE "directory_records"."directory_id" = 20
         AND (organisations.title ILIKE '%текст%' OR directory_values.value ILIKE '%текст2%')
         AND directory_values.field = 'vendor'
   ORDER BY directory_values.value DESC
   LIMIT 10
   OFFSET 0
  ) AS q1
  LEFT JOIN (SELECT
               directory_records.id AS did2,
               directory_values.field,
               directory_values.value,
               directory_values.value_float,
               directory_values.value_int,
               directory_values.value_time

             FROM "directory_values"
               LEFT OUTER JOIN directory_records
                 ON directory_records.id = directory_values.directory_record_id
            ) AS q2
    ON did = q2.did2

How to implement it in ORM RoR?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir, 2016-02-11
@azrail_dev

Do not mind it. Execute as sql query. Well, or think about how to optimize it.
You can also read komar.bitcheese.net/files/1.Manylov_P.-ROR-SQL.pdf

C
cinic, 2016-02-26
@cinic

sql = 'SLECT * FROM blah-blah-blah'
ActiveRecord::Base.connection.execute(sql)

R
Roman Mirilaczvili, 2016-11-07
@2ord

For seed:
stackoverflow.com/questions/5483407/subqueries-in-...
stackoverflow.com/questions/24345959/rails-activer...
or try with Sequel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question