我有这个问题:
SELECT customer.CustomerID, customer.Firstname, customer.LastName, orders.DateOrdered AS LastOrdered, DATEDIFF( CURDATE( ) , MAX( orders.DateOrdered ) ) AS DaysSinseOrdered
FROM customer
LEFT JOIN orders ON customer.CustomerID = orders.CustomerID
where orders.OrdersID IS NULL
GROUP BY customer.CustomerID, customer.FirstName, customer.LastName
UNION
SELECT customer.CustomerID, customer.Firstname, customer.LastName, orders.DateOrdered AS LastOrdered, DATEDIFF( CURDATE( ) , MAX( orders.DateOrdered ) ) AS DaysSinseOrdered
FROM customer
JOIN orders ON customer.CustomerID = orders.CustomerID
GROUP BY customer.CustomerID, customer.FirstName, customer.LastName
ORDER BY DaysSinseOrdered DESC
LIMIT 0 , 30;
显示我需要的信息,但是我可以在没有联合的情况下执行此操作。 我希望它首先显示NULL值,然后显示应用了ORDER BY的第二个查询中的值。现在它将NULL值设为0,并命令所有结果购买ORDER BY;但是我希望它在较大的数字之前位于顶部,就像在这个背景下,它是自上次订购以来的日子,如果你从来没有订购过,那应该是我书中的顶部。
非常感谢任何帮助-Tom
答案 0 :(得分:0)
您实际上不需要UNION
来首先排序空值。您只需先将查询更改为ORDER BY
:
SELECT customer.CustomerID, customer.Firstname, customer.LastName, orders.DateOrdered AS LastOrdered, DATEDIFF( CURDATE( ) , MAX( orders.DateOrdered ) ) AS DaysSinseOrdered
FROM customer
JOIN orders ON customer.CustomerID = orders.CustomerID
GROUP BY customer.CustomerID, customer.FirstName, customer.LastName
ORDER BY orders.OrdersID IS NULL DESC, DaysSinseOrdered DESC
LIMIT 0, 30
因此,此查询将首先排序空值,然后排序非空值。然后,它会将DaysSinseOrdered DESC
作为二级订单 -