0
select * from
(
SELECT DISTINCT ON (table1.id) table1.*, table3.date_filed as date_filed
FROM
        table1 LEFT JOIN table2 ON table2.id = table1.some_id
        INNER JOIN table3 ON table2.id = table3.some_id
WHERE
    (
        status IN('Supervisor Accepted')
    )
    AND(table3.is_main)
)first_result
ORDER BY date_filed ASC LIMIT 25 OFFSET 0

Is there any way to run main/subset query in the database side through Active::record (Rails 3). I don't want run the first_result(First db query) and the order by on the top of the result(Second db query).

I tried the below:

    # First query run   
    first_result = Table1.select('DISTINCT ON (table1.id) table1.*, table3.date_filed').
    joins('LEFT JOIN table2 ON table2.id = table1.some_id'). # I don't want a association here
    joins('INNER JOIN table3 ON table2.id = table3.some_id').
    where('table3.is_main')

    # Second query run, WHICH is UGLY and not working properly
    Table1.where(id: first_result.collect(:&id)).
    order_by('date_filed ASC')
    page(page).
    per_page(per_page)
4
  • question is table1.id not unique for your case, and if yes why? Commented May 23, 2016 at 13:21
  • additionally what is the field is_main of 3rd table? Commented May 23, 2016 at 13:33
  • is_main is just an attribute for filtering. table1.id will not be unique, because of the join (many-to-many association) I will be getting multiple table1 records. Any how the main question is how to run two queries in single execution? Commented May 23, 2016 at 14:12
  • there is the technique to run 2 queries in a single, but. provide yuor models for the tables and their relations, because it is strange what id isn't unique in rails Commented May 23, 2016 at 14:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.