Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting data with a range condition on two columns

Tags:

mysql

i have some articles in my database

+------+--------------+----------+--------+
| id   | article_name | age_from | age_to |
+------+--------------+----------+--------+
| 1337 | article 1    | 30       | 60     |
+------+--------------+----------+--------+
| 1338 | article 2    | 16       | 35     |
+------+--------------+----------+--------+
| 1338 | article 3    | 26       | 28     |
+------+--------------+----------+--------+

The user can set some filters in the front-end. He can search articles that are made for people from 19 years to 22 years. There are also two input fields (Age from and age to). The database should return this:

+------+--------------+----------+--------+
| id   | article_name | age_from | age_to |
+------+--------------+----------+--------+
| 1338 | article 2    | 16       | 35     |
+------+--------------+----------+--------+

How do i do that? i can't do it with WHERE age_from >= 19 AND age_to <= 22.

greetings

like image 837
poldixd Avatar asked Mar 14 '26 15:03

poldixd


1 Answers

Flip the logic:

WHERE age_from <= 22
AND   age_to   >= 19

My favourite explanation of this kind of problem, courtesy of Rudy Limeback (aka r937): http://www.dbforums.com/6318776-post14.html

like image 50
gvee Avatar answered Mar 16 '26 04:03

gvee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!