这是我的表测试,其值为:
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;
我在堆栈溢出上搜索了很多,但没有任何效果。请帮忙。
答案 0 :(得分: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;
答案 1 :(得分: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)
每个选择的括号都是至关重要的。
答案 2 :(得分:0)
使用union,因为此mysql版本不接受子查询中的限制
select * from table where price <=900 limit 2 union select * from table where price > 900 limit 2