if语句有多列选择

时间:2014-03-18 20:42:26

标签: mysql sql

我不知道如何解决这个问题,但是我试图从多个表中选择信息,具体取决于orders表中的数据告诉我的位置,第一个语句有效,但只返回信息来自表orders_bought_a而非orders_bought_b

如果订单来自location a,那么我需要查询以从表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 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以在coalesce()语句中使用select执行所需操作,并对这些联接的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;