MYSQL: How to make NULL or empty data default to 0 during insert

前端 未结 5 2599
走了就别回头了
走了就别回头了 2021-02-20 01:07

So this seems like it would be pretty straight forward and I swear I\'ve done this before, but for some reason it\'s just not working for me.

I am using MAMP

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 01:33

    You can definitely use a trigger for that

    Assuming that you make the field nullable

    CREATE TABLE `listings` (
      `ListingID` int(11) NOT NULL,
      `BathsFull` int(6),              <-----
      PRIMARY KEY (`ListingID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    Trigger

    DELIMITER $$
    CREATE TRIGGER tg_lst_insert BEFORE INSERT ON listings
    FOR EACH ROW
    BEGIN
        SET NEW.BathsFull = IFNULL(NEW.BathsFull, 0);
    END $$
    DELIMITER ; 
    

    Inserting some rows

    INSERT INTO `listings` VALUES(1, '');
    INSERT INTO `listings` VALUES(3, 'a');
    INSERT INTO `listings` VALUES(4, NULL);
    INSERT INTO `listings` (ListingID) VALUES(2);
    INSERT INTO `listings` VALUES(5, 3);
    

    Result

    +-----------+-----------+
    | ListingID | BathsFull |
    +-----------+-----------+
    |         1 |         0 |
    |         2 |         0 |
    |         3 |         0 |
    |         4 |         0 |
    |         5 |         3 |
    +-----------+-----------+
    

提交回复
热议问题