使用DATE和TIME函数对多个表进行排序

时间:2012-06-07 14:22:25

标签: mysql

我在下面的查询中使用了一个联合从三个表中提取数据。

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,但需要一些帮助才能开始。

任何帮助或指示都将不胜感激。

1 个答案:

答案 0 :(得分: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;

它可以帮到你;)