0

I want to select the last two elements in ascending order followed by the first element. Here is my code

   SELECT products.*, locations.logo FROM 
    (SELECT products.* FROM 
    (SELECT products.* FROM products AS products  ORDER BY products.id DESC )
    AS products LEFT JOIN users ON users.id=products.userid WHERE users.hide=0)
    AS products LEFT JOIN locations ON products.location=locations.id LIMIT 2
    UNION SELECT products.*, locations.logo FROM 
    (SELECT products.* FROM 
    (SELECT products.* FROM products AS products  ORDER BY products.id ASC ) 
    AS products LEFT JOIN users ON users.id=products.userid WHERE users.hide=0)
    AS products LEFT JOIN locations ON products.location=locations.id LIMIT 3

E.g. for 20 products now I'm getting

20, 19, 1 (ordered by id).

I'm trying to get 19, 20, 1.

At this moment the above statement works according to the E.g. I know I have to put an ORDER BYclause but I don't know where cause in my trials I'm getting error

"Incorrect usage of UNION and ORDER BY"

Can anybody help me with that?

5
  • i think you cant have order by clause on both select statements when you are doing union. Try to remove order by clause from first select query and try Oct 29, 2013 at 9:06
  • Also order by clause should be last after you have completed making joins. Oct 29, 2013 at 9:07
  • Oh dear. Where to begin? Well I'll start with LIMIT. Except in certain special circumstances LIMIT is meaningless without an ORDER BY clause.
    – Strawberry
    Oct 29, 2013 at 9:18
  • how should I select the last two elements in an ascending order? To do that I have selected in descending order and limited to just 2. Is there another way to do that?
    – Raul
    Oct 29, 2013 at 9:20
  • You have to start over. Consider providing proper DDLs and/or an sqlfiddle TOGETHER WITH THE DESIRED RESULT SET. We can take it from there.
    – Strawberry
    Oct 29, 2013 at 9:22

1 Answer 1

2

You can do something like this

SELECT id
  FROM
(
  (
    SELECT id, 0 sort_order
      FROM Table1
     ORDER BY id DESC
     LIMIT 2
  )
  UNION ALL
  (
    SELECT id, 1 sort_order
      FROM Table1
     ORDER BY id 
     LIMIT 1
  )
) q
 ORDER BY sort_order, id

Output:

| ID |
|----|
| 19 |
| 20 |
|  1 |

Here is SQLFiddle demo

1
  • I adapted my code using your method, tested and it worked perfectly. Excellent answer, clear and easy to remember for the future. Thank you!
    – Raul
    Oct 29, 2013 at 12:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.