MySQL - UNION 2表然后ORDER BY

时间:2014-08-11 07:12:36

标签: mysql database union sql-insert jointable

我正在组合两个查询,我正在使用UNION来组合这两个结果集。

首先查询:

SELECT * FROM (SELECT bsb.ID AS order_item_id, bsb.NAME AS order_item_name, 'line_item' AS order_item_type, bsb.ORDER_ID AS order_id 
  FROM b_sale_basket bsb 
   WHERE bsb.ORDER_ID IN (810, 255)
UNION

第二次查询:

SELECT bso.ID AS order_item_id, bsd.NAME AS order_item_name, 
'shipping' AS order_item_type, bso.ID AS order_id FROM b_sale_order bso 
 LEFT OUTER JOIN b_sale_delivery bsd ON bso.DELIVERY_ID = bsd.ID 
   WHERE bso.ID IN (255, 810)) order_union_result

这两个查询的结果很好,看起来像这样:

image

我尝试在第二个查询的末尾添加一个ORDER BY子句,以便在所有ordered_items之后有一个 SHIPMENT ROW

UNION
SELECT bso.ID AS order_item_id, bsd.NAME AS order_item_name, 'shipping' AS order_item_type, bso.ID AS order_id
FROM b_sale_order bso
LEFT OUTER JOIN b_sale_delivery bsd ON bso.DELIVERY_ID = bsd.ID
WHERE bso.ID IN (255, 810)) order_union_result ORDER by bso.ID

但它提示我错误:#1054 - 'order clause'中的未知列'bso.ID'

结果应如下所示: http://i.stack.imgur.com/ZCfLk.png

注意:我想对行进行排序,以便在所有订购商品之后,它们下面有一个送货行

请帮助我。感谢您的任何帮助

2 个答案:

答案 0 :(得分:0)

试试这个:

ORDER by order_item_id

您应该在ORDER BY子句中使用别名

答案 1 :(得分:0)

使用order_id代替bso.ID。这应该可以解决你的问题。