4

This SQL query gives me the results I want; however, I want the results ordered by a different column:

SELECT * 
FROM post 
    INNER JOIN account ON post.account_id = account.account_id 
WHERE post_id > new 
ORDER BY post_date 
ASC LIMIT 10;

I can not simply change ORDER BY post_date ASC to ORDER BY post_id DESC, while that will in fact order the query the way I want it... it will give me the wrong 10 posts.

I simply want to take the EXACT RESULTS of the above query then reorder the results by the post_id.
I would like to do this with SQL if possible, if not I could order the results by adding the results into a new array reversed.

2
  • Your query should fail, returning MySQL error 1060: Duplicate column name because of the account_id existing in both tables. Commented Mar 1, 2010 at 22:21
  • It did, I made a few changes to the database and it all works like a charm now, thanks for pointing that out! Commented Mar 1, 2010 at 22:38

2 Answers 2

6

Use a subquery to reorder:

SELECT * FROM (
  SELECT *
  FROM post
  INNER JOIN account ON post.account_id = account.account_id
  WHERE post_id > neww
  ORDER BY post_date ASC LIMIT 10;
) ORDER BY post_id
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks worked like a charm, I cant believe I have been searching 2 days for this :(...
Thanks, I thought that this would be the way to go with my own problem (On SQL Server 2k8). You've confirmed it for me. +1
This query is missing AS, should be ... ) AS x ORDER BY post_id. See dev.mysql.com/doc/refman/5.7/en/from-clause-subqueries.html
4

Use a subquery:

SELECT * FROM (
    SELECT *
    FROM post
    INNER JOIN account
    ON post.account_id = account.account_id
    WHERE post_id > neww
    ORDER BY post_date ASC
    LIMIT 10) AS T1
ORDER BY post_id DESC

1 Comment

Wow, Notice the race condition that occurred here. (both posted Mar 1 at 22:13) While both answers are correct only one can get the "correct" answer. I find it interesting that Mark's answer names the sub-query T1 and then doesn't reference it.

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.