我正在使用MySQL的UNION功能检索表结果。该表基本上包含销售订单
中的订购商品以下是我使用的查询:
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
检索 已订购产品上方的第一个查询 order_item_id 255
旁注:如果你问为什么我这样查询它们,因为它们都属于同一个表,这是因为我试图像 woocommerce 对其订购的商品做了...... 上面查询的输出如下所示: http://i.stack.imgur.com/qPsjv.png 但是,我希望订购结果,以便在每个订购的产品下方 数量 每个产品订购以下他们.. 我想要的最终结果,如下所示:
http://i.stack.imgur.com/wx6Aw.png 请帮助我......
而 检索每个产品的数量 数量 已订购
答案 0 :(得分:0)
您可以使用用户定义的变量为每个单独的查询提供排名,因此第一行查询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`
修改强>
您还可以尝试ORDER BY order_item_id,meta_key