简体   繁体   English

在没有组concat的MySQL中将多行合并为一

[英]Combine multiple rows into one in MySQL without group concat

I have a table in MySQL in which I need to join multiple rows. 我在MySQL中有一个表,需要在其中连接多行。 The table look like this: 该表如下所示:

Order_ID  |  Item_ID  |  color
1           1           white
1           2           red
2           1           black
2           1           blue

I want to combine the rows according to their Order_ID which will yield a result that looks like this: 我想根据它们的Order_ID合并行,这将产生如下所示的结果:

Order_ID  |  Item_1_ID  | Item_1_color  | Item_2_ID  | Item_2_color
1           1             white           2            red
2           1             black           1            blue

I know that there's a way to combine two rows into one by using group concat, but I want to do it so that each field remains separated, not joined as if using group concat. 我知道有一种方法可以通过使用组concat将两行合并为一个行,但是我想这样做,以便每个字段都保持分隔,而不是像使用组concat一样联接。

I already tried using statement join too, something like this: 我也已经尝试过使用语句联接,如下所示:

SELECT o.*, o1.* FROM order o INNER JOIN order o1 ON o.Order_ID = o1.Order_ID

But for a few cases the rows that I want to join is too much, exceeding the limit of 61 join in MySQL. 但是在某些情况下,我要连接的行太多,超过了MySQL中61个连接的限制。

Any help would be appreciated, thanks. 任何帮助,将不胜感激,谢谢。

---edit--- - -编辑 - -

There was this other parameter called group which determined the number of items per order. 还有另一个称为组的参数,它确定每个订单的商品数量。 The table looks like this: 该表如下所示:

Order_ID   |  group
 1           1
 2           1

So if the order belongs to the same group they will have the same number of columns, but between one group and another the number of columns may be different. 因此,如果订单属于同一组,则它们将具有相同的列数,但是在一组和另一组之间,列数可能会不同。 And my query is per one group only, so there's no problem in the differences between number of columns. 而且我的查询仅按一组进行,因此列数之间的差异没有问题。

Use GROUP BY order_id , this will group your results and give you the result set you have described. 使用GROUP BY order_id ,这将对结果进行分组并提供您所描述的结果集。

EDIT: 编辑:

According to what you try to accomplish, I'd recommend to you to read about database normalization. 根据您尝试完成的工作,建议您阅读有关数据库规范化的信息。 You do not seem to have a primary key in your table, do you? 您的表中似乎没有主键,对吗? Your table structure honestly does not make any sense, you should store the orders in one seperate table, eg order_id, user_id, ... and then have one table like yours with the items per order and then query for all your orders the items which belong to this order. 老实说,您的表结构没有任何意义,您应该将订单存储在一个单独的表中,例如order_id,user_id,...,然后有一个像您这样的表,其中包含每个订单的商品,然后查询所有订单中的商品属于这个订单。

You don't want to add same results all in one row, but read each row into an array and then loop through the array. 您不想在一行中全部添加相同的结果,而是将每一行读入一个数组,然后遍历该数组。

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

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