SQL to join one table to another table multiple times? (Mapping products to categories)

前端 未结 4 1975
北海茫月
北海茫月 2021-02-04 19:54

Let\'s say I have a Product, Category, and Product_To_Category table. A Product can be in multiple categories.

    Product             


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 20:20

    Seb's answer put me onto the right track for a workaround. I am using Oracle and it has functions which emulate MYSQL's group_concat. Here is an example. This does not generate columns, and thus isn't as good as a pure SQL solution, but it is suitable for my current purposes.

    with data as
    ( 
      select 
        pc.id cat,
        p.id prod, 
        row_number() over( partition by p.id order by pc.id) rn,
        count(*) over (partition by p.id) cnt
      from product_to_category pc, product p
      where pc.product_id = p.id
    )
    select prod, ltrim(sys_connect_by_path(cat, ','), ',') cats
      from data
     where rn = cnt
     start with rn = 1 connect by prior prod = prod and prior rn = rn - 1
     order by prod
    

    This generates data such as

    PROD | CATS
    ===========
    284  |   12
    285  |   12
    286  | 9,12
    

    I can edit the ltrim(sys_connect_by_path()) column as needed to generate whatever data I need.

提交回复
热议问题