我有一個查詢可以處理大部分我需要的內容,但不能爲空結果提供表示邏輯。使用MySQL DAYNAME作爲列標題,即使使用NULL結果
考慮這個查詢:
SELECT
SUM(order_detail.price/order_detail.qty*order_detail.qty_dispatched) AS orderedPrice,
orders.location,
orders.id,
suppliers.supplier_name,
DAYNAME(FROM_UNIXTIME(orders.datetime)) AS Day_Name,
from_unixtime(orders.datetime) AS Day_Date
FROM orders, order_detail, products,suppliers
WHERE (orders.datetime BETWEEN '$from_date' AND '$to_date'
AND order_detail.order_id = orders.id
AND orders.location LIKE '%$locations%'
AND order_detail.product_id=products.id
AND products.supplier_id IN ($suppliers)
AND suppliers.id IN ($suppliers)
AND products.supplier_id=suppliers.id
AND (orders.status <> 'deleted'))
如果我得到的結果爲每天星期我可以用PHP後期處理,並出示結果作爲這樣的:
Location | Supplier Name | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Total
--------------------------------------------------------------------------
Alhambra | Widget Co | $50 | $50 | $50 | $50 | $50 | $50 | $50 | $350
然而,如果在任何一天沒有訂單,我顯然得不到任何結果,並且我不能在後續流程中以一個列中的$ 0的價格出現。
我想也許是一個工作日表可能是一個JOIN的答案,但我無法想象它。像這樣?
CREATE TABLE week_days(
week_day_num INT(11) DEFAULT NULL
);
INSERT INTO week_days(week_day_num) VALUES (1),(2),(3),(4),(5),(6),(7);
SELECT
DAYNAME(FROM_UNIXTIME(orders.datetime)) AS day_name,
SUM(order_detail.price/order_detail.qty*order_detail.qty_dispatched) AS orderedPrice,
COALESCE(SUM(order_detail.price/order_detail.qty*order_detail.qty_dispatched) AS orderedPrice , 0)
FROM week_days wd
LEFT JOIN (
SELECT
orders.location,
orders.id,
suppliers.supplier_name,
from_unixtime(orders.datetime) AS Day_Date
FROM orders, order_detail, products,suppliers
WHERE (orders.datetime BETWEEN '$from_date' AND '$to_date'
AND order_detail.order_id = orders.id
AND orders.location LIKE '%$locations%'
AND order_detail.product_id=products.id
AND products.supplier_id IN ($suppliers)
AND suppliers.id IN ($suppliers)
AND products.supplier_id=suppliers.id
AND (orders.status <> 'deleted'))
) order_results
ON wd.week_day_num = DAYOFWEEK(FROM_UNIXTIME(orders.datetime))
GROUP BY
products.supplier_id,orders.location,DAYOFWEEK(FROM_UNIXTIME(orders.datetime))
ORDER BY location, products.supplier_id,Day_Date ASC;
如果您使用PHP進行透視,爲什麼每天都需要一個結果? PHP可以簡單地執行'if(isset($ data [$ weekday])){顯示那天的結果; } else {display $ 0}'。 – Barmar
我認爲GROUP BY應該進入您的LEFT JOIN並移除「產品」。在你的ORDER BY中。 – etsa
@Barmar每一行都是一天,我需要爲給定周內至少有1個結果的每個位置/供應商合併一週的價值。 –