簡體   English   中英

使用GROUP_CONCAT從多個表派生的mySQL視圖

[英]mySQL view derived from multiple tables with GROUP_CONCAT

如何從以下3個mySQL表中編寫查詢以產生以下mySQL VIEW“清單”:

表: 產品

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

一個簡單的查詢與聯接和一些聚合

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM