0

I'm attempting to do a SQL sort in rails by sorting on a column in multiple tables.

Both Event and Featured models have a column called "date". An event can belong_to a Featured. I'd like to be able to join these two columns together and sort by this date column on both. So if the date of a Featured is 24/05/12 and the date of an Event is 23/05/12, then the Event date would display first.

I'd prefer to do this in SQL (not using a Ruby sort).

Thanks!

Edit:

.order("events.date ASC, featureds.date ASC")

Will not work because this will pull back first the events in order, then the featureds in order.

For example:

Event 1 date: 23/04/12

Event 2 date: 24/04/12

Featured 1 date: 23/04/12

What I want the sql to pull back is:

Event 1 date: 23/04/12

Featured 1 date: 23/04/12

Event 2 date: 24/04/12

Ordering like above will pull it through like so:

Event 1 date: 23/04/12

Event 2 date: 24/04/12

Featured 1 date: 23/04/12

1
  • 1
    Can you post your existing SQL please Commented Dec 28, 2012 at 10:54

1 Answer 1

3

I'm assuming you are using ActiveRecord? Add this to your ActiveRecord query:

.order("events.date ASC, featureds.date ASC")

Table names are my guess.. (featureds?)

Also see the guide.

Sign up to request clarification or add additional context in comments.

3 Comments

That will show the events first and then the featureds which is not what I am trying to achieve. I've updated the original post to reflect what I mean.
I think you cannot retrieve a mix of records like that. The easiest way is to do two queries and join the sets after retrieval.
I ended up creating a separate table that holds the event dates which alleviated the issue.

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.