我想按升序选择最后两个元素,然后是第一个元素。这是我的代码
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。我现在正在购买20种产品
20,19,1(按id排序)。
我想要19,20,1。
此时,上述声明根据例如。我知道我必须提出一个ORDER BY
条款,但我不知道在我的审判中我的错误原因
"Incorrect usage of UNION and ORDER BY"
有人可以帮我吗?
答案 0 :(得分: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
输出:
| ID | |----| | 19 | | 20 | | 1 |
这是 SQLFiddle 演示