我有两张桌子:orders
,orders_others
在orders
中,我有两个重要的列:priority_date
,date_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'
如果我删除条件,它可以正常工作:)
答案 0 :(得分:2)
变量不能直接分配到where {4}之后的条件和位置,所以为此,你可以在having子句中提供条件。
FROM