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

前端 未结 5 2598
走了就别回头了
走了就别回头了 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:21

    If you are explicitly setting the value to NULL in your insert, but want MySQL to replace the NULL with 0, one way to do that is to define the column to allow NULL in the CREATE TABLE statement, and then replace the NULL with a TRIGGER.

    Something like this:

    CREATE TABLE `listings` (
      `ListingID` int(11) NOT NULL,
      `BathsFull` int(6) NULL DEFAULT 0,
      PRIMARY KEY (`ListingID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    delimiter $$
    
    create trigger tr_b_ins_listings before insert on listings for each row
    begin
      set new.BathsFull = coalesce(new.BathsFull,0);
    end $$
    
    delimiter ;
    

    Try it for yourself in this SQL Fiddle

提交回复
热议问题