每个产品一行,包含所有语言字段(来自另一个表)

时间:2018-04-17 20:32:50

标签: mysql sql pivot

我有三张桌子:

products (id) 
products_lang (name)
languages (code)

我希望每个产品都有一行包含所有语言字段。

示例结果:

id, name[es], name[en]

更多信息:

表“产品”

id_product | id_category
1 | 1

表“products_lang”

id_product | id_lang | name
1 | 1 | Car
1 | 2 | Auto

表“语言”:

id_lang | code
1 | en
2 | es

我想要的结果:

id_product | id_category | name (in english) | name (in spanish)
1 | 1 | Car | Auto

只有MySQL才有可能吗?

2 个答案:

答案 0 :(得分:0)

select a.id_product, a.id_category, max(case when code='en' then [name] else null end) [name in english],
max(case when code='es' then [name] else null end) [name in spanish]
from products a join products_lang b on a.id_product=b.id_product
join languages c on b.id_lang=c.id_lang
group by a.id_product, a.id_category

答案 1 :(得分:0)

编辑:在澄清问题的进一步评论后,我的原始答案不再适用。这基本上是一个PIVOT操作。由于MySQL在PIVOT中的优势不那么优雅,我使用了GROUP BYWITH ROLLUP。我还添加了一些孤立的和一些丢失的数据来演示查询将如何处理这些数据。

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE products (id_product int, id_category int) ;
CREATE TABLE products_lang ( id_product int, id_lang int, name varchar(20)) ;
CREATE TABLE languages (id_lang int, code varchar(5)) ;

INSERT INTO products (id_product, id_category)
SELECT 1 AS id_product, 1 AS id_category UNION ALL 
SELECT 2, 1 UNION ALL
SELECT 3, 2
;

INSERT INTO products_lang (id_product, id_lang, name)
SELECT 1 AS id_product, 1 AS id_lang, 'Car' AS name UNION ALL
SELECT 1 , 2 , 'Auto' UNION ALL
SELECT 2 , 1 , 'Car' UNION ALL
SELECT 2 , 2 , 'Auto' UNION ALL
SELECT 3 , 7 , 'voiture' UNION ALL
SELECT 4 , 9 , 'autoa'
;

INSERT INTO languages (id_lang, code)
SELECT 1 AS id_lang, 'en' AS code UNION ALL
SELECT 2, 'es' UNION ALL
SELECT 7, 'fr'
;

查询1

SELECT s1.id_product
  , s1.id_category
  , s1.NameInEnglish
  , s1.NameInSpanish
  , s1.NameInFrench
FROM (
SELECT 
    p.id_product
  , p.id_category
  , MAX(IF(pl.id_lang=1, CONCAT(pl.name, '[', l.code, ']'),'')) AS NameInEnglish
  , MAX(IF(pl.id_lang=2, CONCAT(pl.name, '[', l.code, ']'),'')) AS NameInSpanish
  , MAX(IF(pl.id_lang=7, CONCAT(pl.name, '[', l.code, ']'),'')) AS NameInFrench
FROM products p 
LEFT OUTER JOIN products_lang pl ON p.id_product = pl.id_product
LEFT OUTER JOIN languages l ON pl.id_lang = l.id_lang
GROUP BY p.id_product
WITH ROLLUP
) AS s1
WHERE s1.id_product IS NOT NULL

<强> Results

| id_product | id_category | NameInEnglish | NameInSpanish | NameInFrench |
|------------|-------------|---------------|---------------|--------------|
|          1 |           1 |       Car[en] |      Auto[es] |              |
|          2 |           1 |       Car[en] |      Auto[es] |              |
|          3 |           2 |               |               |  voiture[fr] |