2014-03-18 65 views
1

我不知道如何解決這個問題,但我試圖從多個表中選擇信息,這取決於表格中的數據來自於orders表格,第一個語句可行,但僅限於如果一個訂單來自location a然後我需要查詢抓住從表orders_bought_a信息返回從orders_bought_b如果列表選擇多列

從表orders_bought_a,而不是信息,同樣應該爲location b完成。

有沒有辦法在mysql中執行塊選擇,比如我在首選語句中完成它的方式?

任何幫助將不勝感激,對不起,如果這看起來像一團糟,這是我能做的最好的。

當前聲明:

SELECT oi.id   AS order_item_id, 
     o.status, 
     o.processed, 
     oba.item_id AS buy_item_id, 
     oba.price  AS buy_price, 
     oba.CONDITION AS buy_condition, 
     obb.item_id AS buy_item_id, 
     obb.price  AS buy_price, 
     obb.CONDITION AS buy_condition 
FROM order_items oi 
     LEFT JOIN books b 
       ON oi.isbn = b.isbn 
     LEFT JOIN orders o 
       ON o.id = oi.order_id 
     LEFT JOIN orders_bought_a oba 
       ON oba.id = oi.buy_order_id 
     LEFT JOIN orders_bought_b obb 
       ON obb.id = oi.buy_order_id 
ORDER BY date_ordered DESC 

首選(不工作):

SELECT oi.id AS order_item_id, o.status, o.processed, 

    CASE 
    WHEN(oi.location == 'a') THEN(
     oba.item_id AS buy_item_id, 
     oba.price AS buy_price, 
     oba.condition AS buy_condition 
    ) 

    WHEN(oi.location == 'b') THEN(  
     obb.item_id AS buy_item_id, 
     obb.price AS buy_price, 
     obb.condition AS buy_condition, 
    )  

FROM orders_items oi 
LEFT JOIN books b ON oi.isbn = b.isbn 
LEFT JOIN orders o ON o.id = oi.order_id 
LEFT JOIN orders_bought_a oba ON oba.id = oi.buy_order_id 
LEFT JOIN orders_bought_b obb ON obb.id = oi.buy_order_id 
ORDER BY date_ordered DESC 

回答

1

我建議選擇與來自其他表數據從一個表中的數據,並聯合它。
事情是這樣的:

SELECT oi.id AS order_item_id, o.status, o.processed, 
    oba.item_id AS buy_item_id, 
    oba.price AS buy_price, 
    oba.condition AS buy_condition 

FROM orders_items oi 
LEFT JOIN books b ON oi.isbn = b.isbn 
LEFT JOIN orders o ON o.id = oi.order_id 
LEFT JOIN orders_bought_a oba ON oba.id = oi.buy_order_id 
WHERE oi.location = 'a' 

UNION ALL 

SELECT oi.id AS order_item_id, o.status, o.processed, 
    obb.item_id AS buy_item_id, 
    obb.price AS buy_price, 
    obb.condition AS buy_condition, 

FROM orders_items oi 
LEFT JOIN books b ON oi.isbn = b.isbn 
LEFT JOIN orders o ON o.id = oi.order_id 
LEFT JOIN orders_bought_b obb ON obb.id = oi.buy_order_id 
WHERE oi.location = 'b' 
ORDER BY date_ordered DESC 
+0

謝謝,我應該考慮以前使用UNION,我有時會忘記,但在進行比較時,您需要使用一個等號「oi.location ='b'' –

+0

@ mk_89,更正爲使用單等號 –

0

如果我理解正確的話,你可以做你想要在select聲明coalesce()和少許修改的on條款對那些東西加入:

SELECT oi.id AS order_item_id, o.status, o.processed, 
     coalesce(oba.item_id, obb.item_id) AS buy_item_id, 
     coalesce(oba.price, obb.price) AS buy_price, 
     coalesce(oba.condition, obb.condition) AS buy_condition 
FROM order_items oi LEFT JOIN 
    books b ON oi.isbn = b.isbn LEFT JOIN 
    orders o ON o.id = oi.order_id LEFT JOIN 
    orders_bought_a oba 
    ON oba.id = oi.buy_order_id and 
     oi.location = 'a' LEFT JOIN 
    orders_bought_b obb 
    ON obb.id = oi.buy_order_id and 
     oi.location = 'b' 
ORDER BY date_ordered DESC;