If I use the following UNION queries below I will get the result in several rows... i.e. vertically:
SELECT "Username" AS "Attribute", username AS "Value" FROM users WHERE id = 123
UNION
SELECT "Email" AS "Attribute", email AS "Value" FROM users WHERE id = 123
UNION
SELECT "Name" AS "Attribute", name AS "Value" FROM users WHERE id = 123
UNION
SELECT "Activated" AS "Attribute", activated AS "Value" FROM users WHERE id = 123;
This will result in a "vertical table", like this:
| Attribute | Value |
| --------- | ------------------- |
| Username | UserStephen |
| Email | stephen@example.com |
| Name | Stephen Jones |
| Activated | true |
This works fine of course, but I wonder if there are other methods avaialable in MySQL/MariaDB? If I have 10+ attributes it will be a lot of UNION SELECTs, and a lot of FROM users WHERE id = 123
. I.e. the query becomes quite large, and perhaps ineffective(?).
Can I optimize or simplify the query?
Additional comment: I have a PHP script where I present the result from any query in an HTML table format. I.e. in rows & columns, just as it is returned from the query. In some cases I wan't to present the result vertically, and therefore I want a query that returns the result like this, instead of the fields in columns. I don't want to have to rewrite the PHP script to transpose the table in different situations.