gpt4 book ai didi

MySQL:如果存在则获取大于数字的结果,如果不存在则获取小于数字的结果?

转载 作者:行者123 更新时间:2023-11-29 14:38:41 25 4
gpt4 key购买 nike

我有一个表,将其命名为 MyTable,其中有一列,称为“myvalue”。

我需要一个查询,它接受一个数字并根据与 myvalue 的比较返回一行。

如果 number=myvalue 那么这就是正确的行。如果没有匹配,那么我需要取上面数字的值。如果不存在,我需要取正好低于数字的值。

例如,假设 myvalue 列具有以下值:

100
200
300
400
500

If I query with number=50 it will return the row with '100'.
If I query with number=100 it will return the row with '100'.
If I query with number=101 it will return the row with '200'.
If I query with number=450 it will return the row with '500'.
If I query with number=570 it will return the row with '500'.

到目前为止,我有一个查询,该查询将返回匹配值或其正上方的值,但我不知道如果上面的值不存在,如何使其返回正下方的值?

这就是我现在所做的:

SELECT * FROM MyTable WHERE myvalue >= 'number' ORDER BY myvalue ASC LIMIT 1

(当然将“数字”替换为值)

有什么想法吗?我可以想到一种蛮力方法,但我确信有一些我想不到的优雅方法。

最佳答案

SELECT *
FROM (
(
SELECT *
FROM MyTable
WHERE myvalue >= 'number'
ORDER BY myvalue ASC
LIMIT 1
)
UNION
(
SELECT *
FROM MyTable
WHERE myvalue <= 'number'
ORDER BY myvalue DESC
LIMIT 1
)
) AS temp
ORDER BY myvalue DESC
LIMIT 1

关于MySQL:如果存在则获取大于数字的结果,如果不存在则获取小于数字的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8449683/

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