Q:

return column name with closest value

So I don't know if this is possible, but I would like to return the name of the column which has the closet value to my query.
So this is my table:
--------------------------
| ID | D1 | D2 | D3 | D4 |
--------------------------
| 1  | 0  | 10 | 22 | 50 |
--------------------------

I would like to do a query where I am searching in D1 to D4 for the closest value of 20, in this case D3
Then I would like to return D3 and the value in it.
So my answer should be: 
------
| D3 |
------
| 22 |
------

Is this by any way possible?    

A:

Not easily. Since you've got those as different fields in the same record, you'll have to use very ugly queries:
SELECT source, val, ABS(20 - val) AS diff
FROM (
    SELECT 'd1' AS source, d1 AS val FROM foo
    UNION ALL
    SELECT 'd2', d2 FROM foo
    UNION ALL
    SELECT 'd3', d3 FROM foo
    UNION ALL
    SELECT 'd4', d4 FROM foo
) AS child
ORDER BY diff DESC
LIMIT 1

You should normalize your table, which'd entirely eliminate the entire union business and leave only the outer parent query.

