Can you do if / else logic in a MYSQL statement?

I have soccer players in the database. They each have a rating (1 better) and I am calculating their ages on the fly in a MYSQL query. This query performs an ORDER BY using their rating and their age. So I have this ...

$rankquerytext="ranking + age";

      

Then I have a request ...

$sql = "SELECT *, FLOOR(DATEDIFF(CURDATE(), born) / 365.25) AS age 
    FROM players
    ORDER BY " . $rankquerytext . "";

      

This works great. However, I would like to get a little more specific than just adding their ages to their rankings. For example, I would rather do an if if else in a MySQL query in some way, or just before it, like ...

if (age < 25) {
$ageadjustment=-5;
} else if (age >= 29) {
$ageadjustment= 8;
} else {
$ageadjustment=0;
}

      

And then I would like to add "$ ageadjustment" to their ranking, not to "age".

For example, using "ranking + age", if Calvin Johnson is ranked first, then his final ORDER BY score is 30 (1 + 29).

Ideally, using "rank + $ ageAdjustment" it would be 9 (1 + 8).

Is it doable? I'm limited in my knowledge of mysql, but it doesn't seem doable.

thank

+3


source to share


1 answer


You can use CASE

as below:



$rankquerytext = "ranking + adj";

$sql = "SELECT *,
 CASE WHEN FLOOR(DATEDIFF(CURDATE(), born) / 365.25) < 25 THEN -5 
 WHEN FLOOR(DATEDIFF(CURDATE(), born) / 365.25) >= 29 THEN 8
 ELSE 0 
 END AS adj 
 ORDER BY " . $rankquerytext;

      

+2


source







All Articles