sql >> Database teknologi >  >> RDS >> Oracle

Sammenføj to tabeller med en kolonne med flere poster for den anden tabel

Det er ikke så svært, men - som du fik at vide, så vil du helst IKKE gøre det.

SQL> with
  2  t1 (pk, info) as
  3    (select 1, 'one' from dual union
  4     select 2, 'two' from dual union
  5     select 3, 'three' from dual
  6    ),
  7  t2 (pk, fkt1) as
  8    (select 1, '1,3' from dual union
  9     select 2, '1,2,3' from dual union
 10     select 3, '2' from dual
 11    ),
 12  t2rows as
 13    (select pk, regexp_substr(fkt1, '[^,]+', 1, column_value) fkt1, column_value rn
 14     from t2,
 15          table(cast(multiset(select level from dual
 16                              connect by level <= regexp_count(fkt1, ',') + 1
 17                             ) as sys.odcinumberlist))
 18    )
 19  select t2r.pk,
 20    listagg(t2r.fkt1, ',') within group (order by t2r.rn) fkt1,
 21    listagg(t1.info, ',') within group (order by t2r.rn) infot1
 22  from t2rows t2r join t1 on t2r.fkt1 = t1.pk
 23  group by t2r.pk
 24  order by t2r.pk;

        PK FKT1                 INFOT1
---------- -------------------- --------------------
         1 1,3                  one,three
         2 1,2,3                one,two,three
         3 2                    two

SQL>



  1. MySQL ændrer UTF-8 til ASCII-8BIT

  2. Sådan flettes alle heltalsarrays fra alle poster til enkelt array i postgres

  3. Dummies guide til indlåsning af innodb

  4. Bedste teknik til at cache resultater fra forespørgsler, der ændres sjældent