问题
I have an SQL query that generates the following:
col1 | col2 | col3
=====================
item1 | key1 | value1
---------------------
item1 | key2 | value2
This is the query:
SELECT t1.col1, t2.col2, t2.col3
FROM table1 t1
JOIN table2 t2 ON t1.id = t1.table1_id
Data in table1:
id | col1
=========
1 | item1
2 | item1
Data in table2:
table1_id | col2 | col3
=====================
1 | key1 | item1
1 | key2 | item2
2 | key1 | item1
2 | key2 | item2
2 | key3 | item3
The number of rows is dynamic, so I could also get the following in some cases:
col1 | col2 | col3
=====================
item2 | key1 | value1
---------------------
item2 | key2 | value2
---------------------
item2 | key3 | value3
The way I want the first query to end up as is:
col1 | key1 | key2
=======================
item1 | value1 | value2
And the second query would be:
col1 | key1 | key2 | key3
==============================
item2 | value1 | value2 | value3
Is there an easy way to do this without over-complexing stuff? I am using MariaDB.
回答1:
I think you want this query:
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;
FIDDLE
If you have different items you probably want to group by item
FIDDLE
来源:https://stackoverflow.com/questions/27972461/pivot-rows-into-columns