Matching a value to multiple columns (in one statement) from a table using MySQL

后端 未结 9 1814
无人共我
无人共我 2021-02-08 21:29

I\'m working with a table in MySQL that contains the following columns:

id, january, february, march, april, etc

The data in the table looks li

9条回答
  •  离开以前
    2021-02-08 22:09

    You have to use a Prepared Statement, because what you want to do can only be done with dynamic SQL:

    SET @stmt = 'SELECT * FROM YOUR_TABLE WHERE 1 = 1 '
    SET @stmt = CONCAT(@stmt, (SELECT CONCAT_WS(' AND ', CONCAT(column_name, ' = 1 '))
                                FROM INFORMATION_SCHEMA.COLUMNS
                               WHERE table_name = 'YOUR_TABLE'
                                 AND table_schema = 'db_name'
                                 AND column_name NOT IN ('id'))); 
    
    PREPARE stmt FROM @stmt;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    The first SET statement constructs a basic SELECT statement; the "1 = 1" portion is just there to make it easier to concatenate the "AND column = 1"

    The second SET statement concatenates the contents of the query to get the list of columns based on the table name onto the end of the string in the first SET statement. The idea is that this:

    SELECT CONCAT_WS(' AND ', CONCAT(column_name, ' = 1 '))
      FROM INFORMATION_SCHEMA.COLUMNS
     WHERE table_name = 'YOUR_TABLE'
       AND table_schema = 'db_name'
       AND column_name NOT IN ('id')
    

    ... will return a row that resembles "AND january = 1 AND february = 1 ...". You'd have to update the NOT IN clause if there are other columns you don't want in the WHERE clause.

    The rest is just standard prepared statement stuff, and this all would have to take place within a stored procedure.

提交回复
热议问题