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.
I think you want this query:
FIDDLE
If you have different items you probably want to group by item
FIDDLE