Find column that contains a given value in MySQL

前端 未结 3 1366
太阳男子
太阳男子 2021-01-26 19:10

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

相关标签:
3条回答
  • 2021-01-26 19:46

    Without knowing more about your app, you have several options:

    • Use MySQL's built-in full-text search. You can check the MATCH function in the MySQL documentation.
    • Depending on the needs of your app you could decide to index your whole table with an external full-text search index, like Solr or Sphynx. This provides instant response time, but you'll need to keep the index updated.
    • You can loop through all the columns in the table doing a LIKE query in MySQL (very expensive in CPU and time)
    0 讨论(0)
  • 2021-01-26 19:52

    You're designing this table with repeating groups, which is not satisfying First Normal Form.

    You should create a second table and store the values for column1, column2, and column2 in a single column, on three rows.

    Learn about the rules of database normalization for more details.

    0 讨论(0)
  • 2021-01-26 20:06

    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"

    0 讨论(0)
提交回复
热议问题