我有两个表说X和表Y.X有order_id,offer_id。 order_id可以有多个offer_id。现在我想以这样的方式将数据插入到Y(id,offer_id)中,对于offer_id的每个不同组合,我想要一个id。例如。
表X:
order_id offer_id
2581681 24
2581681 23
2581936 23
2581936 24
2582001 23
2582001 24
2595298 24
2595298 14
2596247 24
2596247 14
2596268 14
2596268 24
1911365 1
1922052 1
1922803 1
1923501 1
1924074 1
1924963 1
表Y应该是这样的:
id offer_id
1 23
1 24
2 14
2 24
3 1
答案 0 :(得分:2)
如果您想要任意数量的优惠,那么问题就很难了。这接近你想要的:
select (@rn := @rn + 1) id, offers
from (select group_concat(distinct x.offer_id order by x.offer_id) as offers
from tableX x
group by x.order_id
) xx cross join
(select @rn := 0) var
group by offers;
这会将商品放在以逗号分隔的列表中的单行上。如果你真的需要它们在不同的行上,我会建立在这个:
select id, substring_index(substring_index(offers, ',', n.n), ',', -1) as offer
from (select (@rn := @rn + 1) id, offers
from (select group_concat(distinct x.offer_id order by x.offer_id) as offers,
count(distinct x.offer_id) as numoffers
from tableX x
group by x.order_id
) xx cross join
(select @rn := 0) var
group by offers
) o join
(select 1 as n union all select 2 as n union all select 3 as n union all select 4 as n
) n
on n.n <= numoffers;
当然,n
子查询需要至少包含订单的最大商品数量。