Search code examples
mysqlcell

Find column that contains a given value in MySQL


I have a table in a MySQL database. I am given a value that occurs as a cell value in that table but I do not know which cell is it i.e. the row and column of that cell. What is the most efficient way to find the column to which that value belongs? Thanks in advance.

Example:

Column_1 | Column_2 | Column_3
1        | 2        | 3
4        | 5        | 6
7        | 8        | 9

Now I am given an input value of "8". I want to know if there is an efficient way to find out that value of "8" belongs to Column_2.


Solution

  • It's a bit strange that you don't know which column the data is in, since columns are meant to have a well-defined function.

    [Original response scrubbed.]

    EDIT: Your updated post just asks for the column. In that case, you don't need the view, and can just run this query

    SELECT col FROM (
       SELECT "Column_1" AS col, Column_1 AS value FROM YourTable
       UNION ALL SELECT "Column_2", Column_2 FROM YourTable
       UNION ALL SELECT "Column_3", Column_3 FROM YourTable
    ) allValues
    WHERE value=8;
    

    When you run this query against your table, it will return "Column_2"