Sql 将行转换为列

Sql 将行转换为列,sql,pivot,mariadb,Sql,Pivot,Mariadb,我有一个生成以下内容的SQL查询: col1 | col2 | col3 ===================== item1 | key1 | value1 --------------------- item1 | key2 | value2 以下是查询: SELECT t1.col1, t2.col2, t2.col3 FROM table1 t1 JOIN table2 t2 ON t1.id = t1.table1_id 表1中的数据: id | col1 =========

我有一个生成以下内容的SQL查询:

col1  | col2 | col3
=====================
item1 | key1 | value1
---------------------
item1 | key2 | value2
以下是查询:

SELECT t1.col1, t2.col2, t2.col3
FROM table1 t1
JOIN table2 t2 ON t1.id = t1.table1_id
表1中的数据:

id | col1
=========
1  | item1
2  | item1
表2中的数据:

table1_id | col2 | col3
=====================
1         | key1 | item1
1         | key2 | item2
2         | key1 | item1
2         | key2 | item2
2         | key3 | item3
行数是动态的,因此在某些情况下,我还可以得到以下结果:

col1  | col2 | col3
=====================
item2 | key1 | value1
---------------------
item2 | key2 | value2
---------------------
item2 | key3 | value3
我希望第一个查询以如下方式结束:

col1  | key1   | key2
=======================
item1 | value1 | value2
第二个问题是:

col1  | key1   | key2   | key3
==============================
item2 | value1 | value2 | value3

有没有一个简单的方法可以做到这一点,而不过度复杂的东西?我正在使用MariaDB。

我想您需要这个查询:

SET SESSION group_concat_max_len = 1000000;

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN t2.col2= ''',
      t2.col2,
      ''' THEN t2.col3 END) AS ',
      t2.col2
    )
   )INTO @sql
FROM  
     t1
JOIN  t2 ON t1.id = t2.table1_id
;


SET @sql=CONCAT('SELECT t1.col1, ',@sql,' FROM   
     t1
JOIN  t2 ON t1.id = t2.table1_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

如果您有不同的项目,您可能希望按项目分组


您可以使用
CASE
,但它可能看起来很麻烦。让我们看看查询!我们不会再为你写整个东西了谷歌“DynamicPivotMariadb”或“DynamicPivotMySQL”。