mySQL视图派生自多个具有GROUP_CONCAT的表

时间:2017-09-28 19:33:11

标签: mysql

我如何编码查询以产生mySQL VIEW'库存'从以下3个mySQL表中可以看到:

表:产品

product_id    category_id   brand
 1              1            Aylmer
 2              2            Ace
 3              2            Weston
 4              1            Campbell
 5              3            Vachon
 6              4            Hero
 7              5            Lactancia
 8              4            Welch
 9              4            Bonne Maman
10              4            Smucker

表:类别

category_id   name_en   name_fr
     1         soup     soupe
     2         bread    pain
     3         cake     gateau
     4         jam      confiture
     5         butter   beurre

表: other_name

other_name_id    category_id     alternate_category
      1               1                 broth
      2               1                 stock
      3               2                 roll
      4               2                 bun
      5               2                 loaf
      6               4                 sweet spread
      7               5                 salty spread

查看:广告资源

product_id   name_en     name_fr      brand       alternate_categories      
       1       soup       soupe       Aylmer        broth; stock
       2       bread      pain        Ace           roll; bun; loaf
       3       bread      pain        Weston        roll; bun; loaf
       4       soup       soupe       Campbell      broth; stock
       5       cake       gateau      Vachon        
       6       jam        confiture   Hero          sweet spread
       7       butter     beurre      Lactancia     salty spread
       8       jam        confiture   Welsh         sweet spread
       9       jam        confiture   Bonne Maman   sweet spread
      10       jam        confiture   Smucker       sweet spread

1 个答案:

答案 0 :(得分:0)

带连接和一些聚合的简单查询

select p.product_id,
c.name_en,
c.name_fr,
p.brand,
group_concat(o.alternate_category separator '; ') alternate_categories
from product p
join category c on(p.category_id = c.category_id)
join other_name o on (c.category_id = o.category_id)
group by p.product_id

DEMO