gpt4 book ai didi

Mysql 选择最后 2 个元素升序,然后是第一个元素

转载 作者:行者123 更新时间:2023-11-29 08:20:03 24 4
gpt4 key购买 nike

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

   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。

此时,上述语句根据 E.g. 起作用。我知道我必须添加一个 ORDER BY 子句,但我不知道在我的试验中出现错误的原因

"Incorrect usage of UNION and ORDER BY"

有人可以帮我吗?

最佳答案

你可以做这样的事情

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 演示

关于Mysql 选择最后 2 个元素升序,然后是第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19653692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com