0

我想按升序选择最后两个元素,然后是第一个元素。这是我的代码

   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

例如,现在我得到了 20 种产品

20、19、1(按 id 排序)。

我正在尝试获得 19、20、1。

目前,上述语句根据例如我知道我必须放置一个ORDER BY子句但我不知道在我的试验中出现错误的原因是什么

"Incorrect usage of UNION and ORDER BY"

有人可以帮我吗?

4

1 回答 1

2

你可以做这样的事情

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

输出:

| 身份证 |
|----|
| 19 |
| 20 |
| 1 |

这是SQLFiddle演示

于 2013-10-29T09:31:38.620 回答