문제

I have two tables say X and table Y. X has order_id,offer_id. An order_id can have more than one offer_id. Now I want to insert data into Y(id,offer_id) in such a way that for every distinct combination of offer_id I want an id. For example.

Table 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

Table Y should be like this :

id     offer_id
1         23
1         24
2         14
2         24
3          1
도움이 되었습니까?

해결책

If you want any number of offers, then the problem is rather hard. This comes close to what you want:

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;

This puts the offers on a single row in a comma delimited list. If you really need them on separate rows, I would then build on this:

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;

Of course, the n subquery needs to have at least the maximum number of offers for an order.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top