MYSQL - 具有案例的最小条件

时间:2017-12-29 10:13:43

标签: php mysql conditional-statements

我有两张桌子:ordersorders_others

orders中,我有两个重要的列:priority_datedate_end

orders_others中,我有一个重要的列:date_to

我希望搜索下一个订单(包含2个表),但下一个日期必须为>= CURRENT DATE

MySQL代码:

SELECT 
    users.*, 
    LEAST(
        MIN(
            CASE WHEN orders.date_end >= CURDATE() THEN orders.date_end ELSE "9999-99-99 99:99:99" END
        ), 
        MIN(
            CASE WHEN orders_others.date_to >= CURDATE() THEN orders_others.date_to ELSE "9999-99-99 99:99:99" END
        ), 
        MIN(
            CASE WHEN orders.priority_date >= CURDATE() THEN orders.priority_date ELSE "9999-99-99 99:99:99" END
        )
    ) as next_order, 
    MIN(
        CASE WHEN orders.date_end >= CURDATE() THEN orders.date_end ELSE "9999-99-99 99:99:99" END
    ) AS next_ending, 
    MIN(
        CASE WHEN orders_others.date_to >= CURDATE() THEN orders_others.date_to ELSE "9999-99-99 99:99:99" END
    ) AS next_order_others, 
    MIN(
        CASE WHEN orders.priority_date >= CURDATE() THEN orders.priority_date ELSE "9999-99-99 99:99:99" END
    ) as next_priority_date
FROM 
    `users` 
    LEFT JOIN `orders` ON `orders`.`idu` = `users`.`id` 
    LEFT JOIN `orders_others` ON `orders_others`.`unique` = `orders`.`unique` 
    AND `orders_others`.`date_to` >= (
        CURDATE() - INTERVAL 1 YEAR
    ) 
WHERE `next_order`>='2017-12-30 00:00:00'
GROUP BY 
    `users`.`id` 
ORDER BY 
    `next_order` ASC 
LIMIT 
    10
  

结果:'where子句'中的未知列'next_order'

如果我删除条件,它可以正常工作:)

1 个答案:

答案 0 :(得分:2)

变量不能直接分配到where {4}之后的条件和位置,所以为此,你可以在having子句中提供条件。

FROM