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

后端 未结 9 1811
无人共我
无人共我 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.

    0 讨论(0)
  • 2021-02-08 22:23

    You can use vectors in MySQL:

    select * from table where (january, february) = (1, 1)
    

    Beware of different server and client collations for text columns, possibly you'll need to specify collation explicitly then.

    0 讨论(0)
  • 2021-02-08 22:23
    select * from table where 1 in (january, february)
    
    0 讨论(0)
提交回复
热议问题