I want to select all the rows in my database but I want them in inverted sequence. Meaning, I want to use the first column data as the new entities and present entities as the first column. I think you got what I mean
Here is an illustration
id | name | marks
-------------------------------
1 | Ram | 45
--------------------------------
2 | Shyam | 87
to
id | 1 | 2 |
----------------------------
Name | Ram | Shyam |
----------------------------
Marks | 45 | 87 |
With a fixed and known columns, here’s how to do it (I took the liberty of naming the table “grades”):
General Idea:
To create a union of different queries and execute it.
Since you need actual data as column headers, the first part of the union will look like:
That query alone will duplicate the result, therefore we need to tell MySQL we need to have 0 rows by adding
LIMIT 0, 0.Our first row of the union will contain
'Name', as well as all the data from “Name” column of the table. To get that line we need a query like:Using the same logic, our second row will look like:
Getting the header:
We need to produce a row from MySQL like:
To get that line we will use CONCAT() and GROUP_CONCAT() functions:
and we’re going to store that line into a new variable:
Creating the lines:
We need to create two queries like the following:
Since we do not know in advance how many rows there are in our original table, we will be using variables to generate the different
LIMIT x, 1statements. They can be produced using the following:Using this snippet, we can create our subqueries:
Which we will put into a variable names @line1, along with the first column data (which is the second column’s name):
By following the same logic, the second line will be:
Combining them all:
Our three variables now contain:
We just need to create a final variable using
CONCAT(), prepare it as a new query and execute it:Entire solution:
(for testing and reference):
Output:
Closing thoughts:
I’m still not sure why you need to transform rows into columns, and I’m sure the solution I presented is not the best one (in terms of performance).
You can even use my solution as a start and adapt it to a general purpose solution where the table column names (and the number of lines) are not known, using
information_schema.COLUMNSas a source, but I guess that’s just going too far.I strongly believe it is much better to put the original table into an array and then rotate that array, thus getting the data in the desired format.