I have a query that returns a small number of rows (usually 2-5) but a huge number of columns (several hundred). The rows are mostly identical, save for a few places. I would like to quickly identify them by hiding columns which are constant (e.g., I have 5 products, all of which cost $3, so the cost column should be suppressed). Is there an elegant way to do this using MySQL? If it helps, most of the columns are numerical.
Here's a tiny example: Suppose my initial query returns
col1|col2|col3|col4
1 | x | a | 3.14
1 | x | b | 3.14
Columns 1, 2 and 4 are "constant", while column 3 is not. Therefore I would like a secondary query to return only column 3:
|col3|
| a |
| b |
The problem is that manually finding a small number of non-constant columns is quite difficult with a large number of constant columns.
Best Answer
Columns are not dynamic. They can't be suppressed on the result because at that point it's too late. You have two options
Unpivot
Becomes
The schema is fixed from that point and you can return just what you need.
Use dynamic SQL. The server returns sql that you issue against the server.
You could also fix the schema, if most of those columns are redundant modify the schema.
Update
I'm very sure I don't misunderstand your goal. We have at least one question a week that is along the same lines we have to turn around for the very same reason. In fact, a year ago yesterday I asked a similar question out of desperation thinking there may be a better way, and was turned around for the same reason.. I can still quote Erwin's relevant parts here,
Your use case here is slightly different, but you should still read the above bolded parts at least 15 times, because it has to sink through.
Then you've got to either,
For your example
What you want is something like this. Note this is not the best way to do this, you could save a round trip by running this in a function.
This seems like a mess, most of that's not me though. We have