I'm using MySQL with PHP. This is like my table: (I'm using 3 values, but there are more)
id | 1 | 2 | 3 ---+---+---+---- 1 | 3 |12 |-29 2 | 5 |8 |8 3 | 99|7 |NULL
I need to get the greatest value's column name in a certain row. It should get:
id | maxcol ---+------- 1 | 2 2 | 2 3 | 1
Are there any queries that will do this? I've been trying, but I can't get it to work right.
Are you looking for something like the
GREATEST
function? For example:Combine it with a
CASE
statement to get column names:It's not pretty. You'd do better to follow Bill Karwin's suggestion and normalize, or simply take care of this in PHP.
This is a great example of the way normalization helps make query design easier. In First Normal Form, you would create another table so all the values would be in one column, on separate rows.
Since you have used repeating groups to store your values across three columns, you can find the column with the greatest value this way:
Forests and trees, here's a trivial and fastest solution (providing I didn't fumble); the expression simply looks for the largest column in the row
a version with IF() would maybe be more readable, but the above should perform a bit better To deal with NULLS an INT value with minimum of -2147483648 was assumed, the expression could be rewritten to deal explicitly with nulls but would have to branch into 8 different cases and is left as an exercise for the OP.
In the php side, you could do something like this:
Or something similar...
The short answer is that there is no simple means to do this via a query. You would need to transpose your data and then determine the largest value that way. So something like:
This solution depends on a fixed set of columns where you basically name the columns in the UNION ALL queries. In addition, if you have two columns with identical values for the same Id, you will get duplicate rows.
This query will return the max value regardless of NULLs
If you really need the column number then
But I think that the last query might perform exceptionally horrible. (Queries are untested)