MySQL 子查询中的查询添加限制

MySQL Query add limit in SubQuery

这是我的 table 测试值:

Price
----------
300
600
900
1000
1800
2000

我想查询当我搜索 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;

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

使用 union 因为此 mysql 版本不接受子查询中的限制

select * from table where price <=900 limit 2 union select * from table where price > 900 limit 2

MySQL 不支持 WHERE IN/EXSISTS/ANY/SOME 子查询中的 LIMIT,您可以使用 UNION

来实现
(SELECT * /* this should be a columnlist */
 FROM tablename
 WHERE price < 900
 ORDER BY price LIMIT 2)

 UNION

(SELECT * /* this should be a columnlist */
 FROM tablename
 WHERE price >= 900
 ORDER BY price LIMIT 2)

每个 select 两边的括号很重要。

See SQL Fiddle

您可以尝试以下方法...

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;