I have a big MySQL query which is formed with PHP.
I don't like that this big IF statement repeats 4 times in a query (saved in $endTrialDate variable).
And I want to make it shorter and nicer, just using MySQL variables.
My Query (EDITED AND SIMPLIFIED):
$endTrialDateCondition = "IF(ec.extend_trial_type LIKE 'week',
ADDDATE(ec.start_contract, (7 * ec.extend_trial_time)),
IF(ec.extend_trial_type LIKE 'day',
ADDDATE(ec.start_contract, ec.extend_trial_time),
ADDDATE(ec.start_contract, INTERVAL ec.extend_trial_time MONTH)
)
)";
$endTrialDate = "(SUBDATE((".$endTrialDateCondition."), 1))";
$finalQuery = "SELECT e.firstname_employe, e.lastname_employe,
".$endTrialDate." as end_trial_date
FROM employe_contract ec
LEFT JOIN employe e ON ec.id_employe = e.id_employe
WHERE ".$endTrialDate." >= ?
AND ".$endTrialDate." <= ?
ORDER BY ".$endTrialDate.", e.lastname_employe, e.firstname_employe";
When I tried to modify my query like: (using variable @end_trial_date)
$finalQuery = "SELECT e.firstname_employe, e.lastname_employe,
@end_trial_date := ".$endTrialDate." as end_trial_date
FROM employe_contract ec
LEFT JOIN employe e ON ec.id_employe = e.id_employe
WHERE @end_trial_date >= ?
AND @end_trial_date <= ?
ORDER BY @end_trial_date, e.lastname_employe, e.firstname_employe";
end_trial_date in results was NULL, so nothing was found.
How to make this query shorter?
SELECTquery on a row by row basis as you are. Or, to put it in other terms: theORDER BYis performed after all the rows have been selected, so the variable there won't have the content you expect.