我想make sql查询,它将搜索数据库以找到多个最接近的值 我有以下查询来查找最接近的值。
SELECT * FROM table
WHERE price >= (50 * .9) and price <= (50 * 1.1)
order by abs(price - 50) LIMIT 1;
它的工作正常,但我想让它搜索多个值,如:
SELECT * FROM table
WHERE price >= (50 * .9) and price <= (50 * 1.1) //here i want one result (limit 1)
or price >= (50 * 1.9) and price <= (50 * 2.1) //here i want one result (limit 1)
order by abs(price - 50)
我希望每个价格限制1找不到所有值。 我怎么能这样做?
//编辑 刚刚找到答案。
(select *
from table
WHERE price >= (50 * .9) and price <= (50 * 1.1)
order by abs(price - 50)
limit 1
) union all
(select *
from table
WHERE price >= (50 * 1.9) and price <= (50 * 2.1)
order by abs(price - 50)
limit 1
)
答案 0 :(得分:1)
SELECT * FROM table
WHERE price >= (50 * .9) and price <= (50 * 1.1) //here i want one result (limit 1)
union
SELECT * FROM table
WHERE price >= (50 * 1.9) and price <= (50 * 2.1) //here i want one result (limit 1)
order by abs(price - 50)
答案 1 :(得分:0)
如何使用union all
?
(SELECT *
FROM table
WHERE price >= (50 * 0.9) and price <= (50 * 1.1)
ORDER BY ABS(price - 50)
LIMIT 1
) UNION ALL
(SELECT *
FROM table
WHERE price >= (50 * 1.9) and price <= (50 * 2.1)
ORDER BY ABS(price - 2*50)
LIMIT 1
) ;