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

后端 未结 9 1818
无人共我
无人共我 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:11

    Try to create view

    CREATE VIEW v_months 
    AS 
    SELECT *, CONCAT( CAST(jan AS CHAR(1)), 
                      CAST(feb AS CHAR(1)),
                      CAST(mar AS CHAR(1)),
                      ...) AS all 
    FROM months
    

    You will get something like this:

    aa, 0, 0, 1, 0, 0010
    ab, 1, 0, 1, 0, 1010
    ac, 1, 1, 0, 0, 1100
    ad, 1, 1, 1, 0, 1110
    

    And then you can query

    SELECT * FROM v_months WHERE all = '100110010101'
    

    Or if you want query "get all rows, where feb = 1", you can write like this:

    SELECT * FROM v_months WHERE all LIKE '_1____________'    
    

    where '_' matches exactly one character.

提交回复
热议问题