My case is as follow:
I have a table articles with these details:
article | image1 | image2 | image3
---------------------------------
1 | im-x
2 | im-y
3 | im-z
and other article_images table with this data:
article | image
---------------
1 | im-a
1 | im-b
2 | im-c
2 | im-d
3 | im-e
I need to update the table articles like this:
article | image1 | image2 | image3
---------------------------------
1 | im-x | im-a | im-b
2 | im-y | im-c | im-d
3 | im-z | im-e |
I know it seems not very difficult, but impossible to find an example on google. Can anyone help me, please?
This query will produce the desired Pivot:
A bit complicated, but this subquery will work in MySQL + PostgreSQL.
To update use (this
UPDATEis MySQL specific):If your database support window functions + CTE, like SQL Server, PostgreSQL or ORACLE, the following query can be used instead to generate Pivot:
Now you have a single row per article in a shorter way and you can use this subquery to update:
This
UPDATEquery will work in PostgreSQL, but likely it wont on ORACLE / SQL Server.You can play around with MySQL and PostgreSQL variants.