Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Order by date from 2 tables

I have two tables that I am joining together, each table has a date in which the item was added. What I would like to do is order the rows by last activity using the date column from both tables kind of like a forum. Someone asks a question, and the question is at the top of the board, as new questions get asked they get put to the top of the board. Questions move down, and once someone posts an answer to it it moves back to the top of the board. How can I formulate a query to do something like this? Here is what I have so far:

select question, question_id, count(a.answer_id) total
from questions q
left join answers a using(question_id)
group by q.question_id order by question_id desc limit 10

Upvotes: 1

Views: 53

Answers (1)

beder
beder

Reputation: 1074

Correct me if I'm wrong, but you only need to use the date from questions to order, when there is no answer.

In this case:

order by COALESCE(a.date, q.date) desc

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

On second thought, this would cause your query to fail because q.date and a.date are not in your group by. Adding q.date to the group by is OK, but adding a.date to the group by would make the same question appear as much times as there are answers.

So you should change your join to something like:

left join (select question_id, max(date) as date from answers group by question_id) a
 on a.question_id = q.question_id

And then use the order by I suggested

Upvotes: 2

Related Questions