2

Here is my table test with values:

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

I want to query such that when I search for 300 ,I should get 4 records 300,600,900,1000.

If I search for 900, I can get 600,900,1000,1800. i.e. Two records <=900 and Two record >900

Here is the query I tried :

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;

I searched a lot on stack overflow,but nothing worked. Please help .

3 Answers 3

5

You can try the following...

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;
Sign up to request clarification or add additional context in comments.

1 Comment

can i have more specification regarding this Question bcz i stuck in query ??
2

MySQL doesn't support LIMIT in WHERE IN/EXSISTS/ANY/SOME subqueries, you can do this with 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)

The parenthesis around each select are crucial.

See SQL Fiddle

6 Comments

Yes I know. Isn't there any other workaround to it except UNION ?
In this case,order by do not work.I get Error "Incorrect usage of UNION and ORDER BY"
Just checked the MySQL documentation and there's an example exactly the same way, but maybe it's caused by SELECT *.
Can I use join ? I am not so good at JOINs ,If you can help :)
Yes you can, but why should you. Its not less inefficient then union. I've added a link to a fiddle in my answer, and there are no errors
|
0

Using union because this mysql version don't accept limit in subqueries

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

1 Comment

Please edit your answer and include some explanation in it. Code-only answers are sometimes good enough, but code+explanation answers are always better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.