我不知道如何解决这个问题,但是我试图从多个表中选择信息,具体取决于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
答案 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;