How do I select a column value as a column name and group the results as a row.
I have a table as such:
id articleId label value
1 1 title Example title
2 1 description This is the description
3 1 author Me
4 2 title Example of another type of article
5 2 description Short description
6 2 author Someone else
Is it possible to select all of the rows and use the label as the column name and the value as the value of that column name and then group them by the article name.
So how I would like to have it returned:
articleId title description author
1 Example title This is the.. Me
2 Example of an.. Short descr.. Someone else
I’m using this for a CMS where the user can define the fields for an article so we don’t have to customize the table’s. This is why i’m not making the tables as the I would like to have it returned. I am also aware that I can just as easily convert the result to this in php.
— edit —
Can this be done without knowing what labels are added? In this example im using title, description and author. But it could very well be something totally different like title, shortDescription, availableTo, techInformation, etc.. The idea is that the article’s are customizable for the user without needing to change the database and query’s
I figured I’d better post as an answer, even if not what OP would like to hear. What you are asking to do is to populate a query with a variable number of columns based on the distinct values within column
label, all associated with articleID. Taking your specific example, the following would be the resultant query that I would most likely go to in this instance (though the example from @Devart is equally valid)Now expanding this to account for up to n labels, we get the following query (metacode included, this query will NOT execute verbatim)
So what you can do is one of the following.
SELECT t.* FROM tablename tand then have PHP process it as requiredSELECT DISTINCT label FROM tablenameand have PHP build the second query with the manyLEFT JOINs (orMAX/GROUP BYlogic if preferred)