我有一个名为价格
的列,我想输入价格并获取下一个最昂贵的商品,或者如果输入的价格超出表中可用的范围,则显示最昂贵的商品。
例如,我的表中有以下项目
id category price
1 Toys 12
2 Toys 14
3 Toys 18
4 Toys 40
5 Toys 38
6 Toys 67
因此,如果我输入 20,我希望返回玩具编号 5(价格 38),因为这是下一个大数字。如果我输入的价格超出了表格的范围,例如100 那么我想退回最贵的元素,即玩具编号 6。
目前我有一个类似的查询
select *
from items
where category = ? and price > ?
order by price limit 1;
这将返回下一个最昂贵的玩具或任何其他类别的任何其他元素,但如果我输入 100 那么我将如何显示最昂贵的元素?价格栏上可以有多个或
吗?
重要:如果可能的话,我希望在不使用合并或 null 条件的情况下实现此目的
最佳答案
这是一种方法:
select i.*
from items i
where category = ?
order by (price > ?) desc,
(case when price > ? then price end) asc,
price desc
limit 1;
但是,更好的方法(就性能而言)可能是这样的:
(select i.*
from items i
where category = ? and price > ?
order by price asc
limit 1
) union all
(select i.*
from items i
where category = ?
order by price desc
limit 1
)
order by price
limit 1;
如果第一个子查询不返回任何行,第二个子查询将会返回任何行。对两行进行排序的开销是最小的(每个子查询limit 1
)。而且,这应该充分利用两个子查询的 items(category, Price)
索引。
关于mysql - 如何在同一列上有多个 OR 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226263/