0

我尝试在导出为 csv 格式之前生成数据,但我未能获得正确的数据。

Table : products
products_id | products_image
    2       |    a.jpg
  1786      |    b.jpg

Table : product_description
products_id | products_description  | language_id
     2      |   BM description      |      6
   1786     |   BM description      |      6
   1786     |   CN description      |      4
   1786     |   EN description      |      1

我试图得到这样的输出:

products_id | products_image | p_description_6 | p_description_4 | p_description_1 |
    2       |     a.jpg      | BM description  |                 |                 |
    1786    |     b.jpg      | BM description  | CN description  | EN description  |

我当前的查询如下,但此查询未能在同一行中生成 product_description:

$select = "SELECT p.*, pd.* FROM products p LEFT JOIN product_description pd on p.products_id=pd.products_id group by p.products_id";
4

2 回答 2

1

尝试类似的东西,

SELECT
    P.products_id,
    p.products_image,
    MAX(CASE WHEN language_id = 6 THEN products_description  END) AS p_description_6,
    MAX(CASE WHEN language_id = 4 THEN products_description  END) AS p_description_4,
    MAX(CASE WHEN language_id = 1 THEN products_description  END) AS p_description_1

FROM 
    products P 

INNER JOIN 
    product_description D ON P.products_id = D.products_id

GROUP BY 
    P.products_id,
    p.products_image

SQL小提琴

于 2013-04-09T03:07:46.263 回答
0

您可以使用GROUP_CONCAT在同一行中生成 product_description:

select 
  a.products_id,
  a.products_image,
  group_concat(b.products_description) as descriptions,
  group_concat(b.language_id) as lang_ids
from products a 
left join 
  product_description b on b.products_id = a.products_id
group by a.products_id

SQL 小提琴演示

于 2013-04-09T03:26:50.807 回答