简体   繁体   English

MySQL-UNION和ORDER / SORT行

[英]MySQL - UNION and ORDER/SORT ROWS

I am retrieving table result/s using MySQL's UNION feature. 我正在使用MySQL的UNION功能检索表结果。 The table is basically containing ordered items from a sales order 该表基本上包含销售订单中的订购商品

Below is the query that i Used: 以下是我使用的查询:

SET @meta_id=0; 
SELECT bsb.ID AS meta_id, bsb.ORDER_ID AS order_item_id, '_product_id' AS meta_key, bsb.PRODUCT_ID AS meta_value, 1 AS origin
FROM b_sale_basket bsb
WHERE bsb.ORDER_ID = 255
UNION
SELECT bsb.ID AS meta_id, bsb.ORDER_ID AS order_item_id, '_qty' AS meta_key, bsb.QUANTITY AS meta_value, 2 AS origin
FROM b_sale_basket bsb
WHERE bsb.ORDER_ID = 255
) sales_order_meta 

The first query above retrieves ordered products having an order_item_id of 255 上面的第一个查询检索 order_item_id255的 订购产品
while
The second query above retrieves the quantity of each product ordered 上面的第二个查询检索 订购的每种产品的数量

Side Note : In case you ask why I query them this way since they all belong in the same table, it is because I'm trying to retrieve it like woocommerce does to its ordered items... 注意 :如果您问为什么我要查询它们,因为它们都属于同一个表,那是因为我试图像woocommerce一样对其进行检索...

The output of the query above looks like this: 上面查询的输出如下所示:

http://i.stack.imgur.com/qPsjv.png http://i.stack.imgur.com/qPsjv.png

But, I wish to order the results so that below each product ordered there is a quantity of each product ordered below them.. 但是,我希望订购结果,以便在订购每种产品下方 都有 一定数量的订购的每种产品。

The Final result that I want, looks like this: http://i.stack.imgur.com/wx6Aw.png 我想要的最终结果如下所示: http : //i.stack.imgur.com/wx6Aw.png

Kindly Please help me... 请帮助我...

You can use a user-defined variable to give a rank for each individual query so first row query 1 will have a rank of 1 and similarly first row of second query will have a rank of 1 and then 2 ,3 so on and then order your result by this row number 您可以使用用户定义的变量为每个查询提供排名,因此第一行查询1的排名为1,类似地,第二查询的第一行的排名为1,然后为2,3,依此类推,然后进行排序您通过该行号得到的结果

SELECT bsb.ID AS meta_id, bsb.ORDER_ID AS order_item_id, '_product_id' AS meta_key, bsb.PRODUCT_ID AS meta_value, 1 AS origin
,@r:= @r +1 AS `row`
FROM b_sale_basket bsb,(SELECT @r:=0) t
WHERE bsb.ORDER_ID = 255
UNION
SELECT bsb.ID AS meta_id, bsb.ORDER_ID AS order_item_id, '_qty' AS meta_key, bsb.QUANTITY AS meta_value, 2 AS origin
,@r:= @r +1 AS `row`
FROM b_sale_basket bsb,(SELECT @r:=0) t
WHERE bsb.ORDER_ID = 255
ORDER BY `row`

Edit 编辑

You can also try ORDER BY order_item_id,meta_key 您也可以尝试ORDER BY order_item_id,meta_key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM