LoginSignup
6
5

More than 5 years have passed since last update.

column cannot be null

Posted at

通常はnot null制約のカラムに対してnullを入れようとして起こられるエラーですが、これがトリガー経由でも同じエラーが出るようです

sampleのSQLを下記で用意

historyテーブルのflagが0->1になった時にsummaryテーブルに値が加算されます

CREATE TABLE `history` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`a_id` INT(10) DEFAULT NULL,
`b_id` INT(10) DEFAULT NULL,
`flag` tinyint(4) DEFAULT NULL,
`last_update` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `id` )
) DEFAULT CHARSET=utf8;

CREATE TABLE `summary` (
`a_id` INT(10) NOT NULL,
`b_id` INT(10) NOT NULL,
`sum` INT(10) default null,
 PRIMARY KEY (`a_id`,`b_id`)
) DEFAULT CHARSET=utf8;

DELIMITER $$
CREATE TRIGGER before_update_history BEFORE UPDATE ON history
FOR EACH ROW
BEGIN
  IF NEW.flag = 1 AND OLD.flag = 0 THEN
    INSERT INTO summary ( a_id, b_id, sum )
      VALUES ( new.a_id, new.b_id , 1 )
    ON DUPLICATE KEY UPDATE
      sum = sum + 1;
  END IF;
END;
$$
DELIMITER ;

通常であればhistoryテーブルをflag=1で更新すればsummaryテーブルも更新されます

mysql> insert into history (a_id,b_id,flag) values ( 1, 1, 0 );
mysql> select * from history;
+----+------+------+------+---------------------+
| id | a_id | b_id | flag | last_update         |
+----+------+------+------+---------------------+
|  1 |    1 |    1 |    0 | 2015-08-12 16:43:45 |
+----+------+------+------+---------------------+
mysql> update history set flag=1 where id=1;
mysql> select * from history;
+----+------+------+------+---------------------+
| id | a_id | b_id | flag | last_update         |
+----+------+------+------+---------------------+
|  1 |    1 |    1 |    1 | 2015-08-12 16:43:52 |
+----+------+------+------+---------------------+
mysql> select * from summary;
+------+------+------+
| a_id | b_id | sum  |
+------+------+------+
|    1 |    1 |    1 |
+------+------+------+

ここでb_idがnullのレコードを挿入して、flagを1にしてトリガーを動作させます

mysql> insert into history (a_id,flag) values ( 1, 0 );
mysql> select * from history;
+----+------+------+------+---------------------+
| id | a_id | b_id | flag | last_update         |
+----+------+------+------+---------------------+
|  1 |    1 |    1 |    1 | 2015-08-12 16:43:52 |
|  2 |    1 | NULL |    0 | 2015-08-12 16:46:25 |
+----+------+------+------+---------------------+
mysql> update history set flag=1 where id=2;
ERROR 1048 (23000): Column 'b_id' cannot be null

もちろん普通にnullを突っ込もうとしても同じエラーになるようです

mysql> insert into summary ( a_id, b_id, sum ) values ( 1, null, 1 );
ERROR 1048 (23000): Column 'b_id' cannot be null

開発時や、例外時にこういうパターンに陥ってしまった時に見つけるまで時間がかかったのでメモとして残しておきます

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5