0

我有下面的查询,它使用联合从三个表中提取数据。

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

我正在尝试将下面的函数写入 SQL,以便我可以按颜色对结果进行排序。

我的 PHP 示例函数如下。

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";
}

我已经研究过使用 CASE SELECT 和 IF STATEMENTS 但需要一点帮助才能开始。

任何帮助或方向将不胜感激。

4

1 回答 1

1

我不会为您提供开箱即用的解决方案,但请考虑以下查询:

SELECT
    IF(DATEDIFF(TODAY, YESTERDAY) <= 7, "green",
        IF(DATEDIFF(TODAY, YESTERDAY) <= 14, "orange",
            "red")) as COLOUR
FROM (
    SELECT
    NOW() as TODAY,
    DATE_SUB(NOW(), INTERVAL 15 DAY) as YESTERDAY) T;

它应该可以帮助你;)

于 2012-06-07T15:15:17.710 回答