MySQL Query在SubQuery中添加限制

MaN*_*aNn 2 mysql subquery

这是我的表测试值:

Price
----------
300
600
900
1000
1800
2000
Run Code Online (Sandbox Code Playgroud)

我想查询,当我搜索300时,我应该得到4条记录300,600,900,1000.

如果我搜索900,我可以获得600,900,1000,1800.即两条记录<= 900,两条记录> 900

这是我试过的查询:

SELECT * FROM table h where CONDITIONS 
 and  (price in (select price from table where price <=900) // I want to add   LIMIT 2 in this subquery
 or price in (select price from table where price >900)//LIMIT 2
)
order by FIELD(price ,900) DESC limit 5;
Run Code Online (Sandbox Code Playgroud)

我在堆栈溢出上搜索了很多,但没有任何效果.请帮忙 .

Far*_*enP 5

你可以试试以下......

select * from ((select h.* from table_name h where amount <=300 order by amount desc limit 2)
union
(select h.* from table_name h where amount >300 order by amount limit 2)) 
derived_table order by FIELD(amount,300) desc;
Run Code Online (Sandbox Code Playgroud)