I have the query below which uses a union to pull data from three tables.
SELECT * FROM (SELECT
*,'table1' AS 'tbl', colour AS get_colour(created_date) FROM table1 WHERE customer = '11' UNION SELECT
*,'table2' AS 'tbl', colour AS get_colour(created_date) FROM table2 WHERE customer = '11' UNION SELECT
*,'table3' AS 'tbl', colour AS get_colour(created_date) FROM table5 WHERE customer = '11'
ORDER BY colour ASC
) as c
I am trying write the function below into SQL so that I can sort my results by colour.
My PHP example function is as follows.
function get_colour($date) {
$days = floor((time() - strtotime($date))/(60*60*24));
if(empty($date) || $date == "-") return "grey";
elseif($days <= 7) return "green";
elseif($days <= 14) return "orange";
else return "red";
}
I have looked into using CASE SELECT and IF STATEMENTS but need a little help getting started.
Any help or direction would be appreciated.
I won’t give you an out-of-the-box solution but consider this query:
It should help you 😉