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

强颜欢笑 提交于 2019-12-04 03:28:52

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 |
+-----------+-----------+

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

You can use the default keyword to get the default value of the column during insertion.

Example :

INSERT INTO listings(ListingID, BathsFull) VALUES (2,DEFAULT);

Maybe you should try this:

insert into listings (ListingID, ListingID, BathsFull) 
values (@listing_id, @ListingID, isnull(BathsFull, 0)

You forgot to post the INSERT queries but I'm sure the problem is there. This works as expected:

insert into listings (ListingID) values(1)

... because you omit BathsFull so MySQL uses the defalt. This doesn't:

insert into listings (ListingID, BathsFull) values(1, null);

... because your are telling MySQL that you want NULL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!