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

后端 未结 9 1837
无人共我
无人共我 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 21:59

    How about solving the problem with a VIEW?

    CREATE TABLE `d001ab05`.`months` (
    `id` INT NOT NULL ,
    `jan` BOOL NOT NULL ,
    `feb` BOOL NOT NULL ,
    `mar` BOOL NOT NULL ,
    `apr` BOOL NOT NULL ,
    `may` BOOL NOT NULL ,
    `jun` BOOL NOT NULL ,
    `jul` BOOL NOT NULL ,
    `aug` BOOL NOT NULL ,
    `sep` BOOL NOT NULL ,
    `oct` BOOL NOT NULL ,
    `nov` BOOL NOT NULL ,
    `dec` BOOL NOT NULL ,
    PRIMARY KEY ( `id` )
    ) ENGINE = InnoDB;
    

    Insert data:

    INSERT INTO `d001ab05`.`months` (
    `id`, `jan`, `feb`, `mar`, `apr`, `may`, `jun`,
    `jul`, `aug`, `sep`, `oct`, `nov`, `dec`
    ) VALUES (
    '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'
    ), (
    '2', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'
    ), (
    '3', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'
    ), (
    '4', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'
    );
    

    View with Select:

    CREATE OR REPLACE VIEW `moncase` AS
    SELECT id,
    CASE WHEN `jan` =1 OR `feb` =1 OR `mar` =1 OR `apr` =1 OR `may` =1 OR
    `jun` =1 OR `jul` =1 OR `aug` =1 OR `sep` =1 OR `oct` =1 OR `nov` =1 OR `dec` =1
    THEN 1 ELSE 0 END AS or_over_months
    FROM months;
    

    Select:

    SELECT * FROM `moncase` WHERE `or_over_months` = 1;
    

    Result:

    id | or_over_months
    1  | 1
    2  | 1
    4  | 1
    

提交回复
热议问题