how to save the result of a subquery in mysql in order to compare it

0

I have a query from the users table. Among its fields I have a field called "fechadenacimiento", through a subquery I get the age and I show it in the results. Note that this value does not exist in the table I get it on the fly, however I need to be able to save it (or set it up) to be able to make type filters:

 where edad > 18 || edad < 22

This is my query.

select u.id, u.nombre, u.rfc as cu, u.nombre as estado, u.categoria, u.fnacimiento, YEAR(CURDATE())-YEAR(d.fnacimiento) as edad
from usuarios as u

I need to do something like this:

select u.id, u.nombre, u.rfc as cu, u.nombre as estado, u.categoria, u.fnacimiento, YEAR(CURDATE())-YEAR(d.fnacimiento) as edad
from usuarios as u where edad > 18 && <30

Is this possible?

Thank you.

    
asked by Neftali Acosta 23.11.2018 в 11:20
source

4 answers

2

Use the same function in the where with a BETWEEN

select u.id, u.nombre, u.rfc as cu, u.nombre as estado, u.categoria, u.fnacimiento, YEAR(CURDATE())-YEAR(d.fnacimiento) as edad
from usuarios as u where YEAR(CURDATE())-YEAR(d.fnacimiento) BETWEEN 19 AND 29
    
answered by 23.11.2018 / 11:39
source
3

Another way to do it would be to use HAVING , in the following way:

SELECT 
    u.id, 
    u.nombre, 
    u.rfc cu, 
    u.nombre estado, 
    u.categoria, 
    u.fnacimiento, 
    TIMESTAMPDIFF(YEAR, u.fnacimiento, CURDATE()) edad
FROM usuarios u 
HAVING edad BETWEEN 18 AND 30;
  • I recommend that you use a more SQL style, with BETWEEN .
  • The use of TIMESTAMPDIFF will provide more accurate data, especially when the time matters. If you were born the day X at the hour Y , until the hour Y you have not turned years:)

Test code

SEE DEMO IN REXTESTER

    
answered by 23.11.2018 в 11:50
2

I see two ways (there are more in reality but they are more convoluted)

One: put the same formula in the WHERE

select u.id, u.nombre, u.rfc as cu, u.nombre as estado, u.categoria, u.fnacimiento, YEAR(CURDATE())-YEAR(d.fnacimiento) as edad
from usuarios as u
where ( YEAR(CURDATE())-YEAR(d.fnacimiento) ) between 19 AND 29

Note that I used 19 and 29 because you are using a condition that does not include 18 or 30.

Two: wraps the entire main query as subquery

SELECT * FROM 
(select u.id, u.nombre, u.rfc as cu, u.nombre as estado, u.categoria, u.fnacimiento, YEAR(CURDATE())-YEAR(d.fnacimiento) as edad
from usuarios as u) aux
WHERE edad>18 AND edad<30

Another alternative would be for example to declare a variable and update it in each record to the value of age.

    
answered by 23.11.2018 в 11:41
2

I try to answer from the app I regret but it is correctly indented, but try this

select obj1.*
    from (


select u.id, u.nombre, u.rfc as cu, u.nombre as estado, u.categoria, u.fnacimiento, YEAR(CURDATE())-YEAR(d.fnacimiento) as edad from usuarios as u

    )obj1
    Where obj1.edad >18 AND obj1.edad<30
    
answered by 23.11.2018 в 12:10