1. 程式人生 > 其它 >MySQL欄位約束和null值注意事項

MySQL欄位約束和null值注意事項

欄位約束

  1. unsigned 無符號 只能儲存正數

    只能用於數值型別 不允許出現負數 長度增加一倍

     CREATE TABLE `test` (
      `age` tinyint(4) DEFAULT NULL,
      `newage` tinyint(3) unsigned DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    
  2. zerofill 零填充

    只能用於數值型別 當儲存的資料長度不足 使用零填充

    alter table test add zf int(5) zerofill;
    insert into test(zf) values(12345);
    
  3. auto_incement 自增

    用於設定欄位的自動增長 每增加一條記錄 該欄位的值會自動加1(用於設定主鍵)

    create table test2(
        -> id int primary key auto_increment,
        -> username varchar(10) default 'xxx'
        -> );
    insert into test2 values(null, 'xxx');
    insert into test2(username) values('xxx');
    

    注意:

    • 需要配合我們的主鍵索引使用
    • 插入資料無需給值 增長的步長預設為1
  4. default 預設值

    當不給該欄位插入值 則值為預設值 否則值為你所給定的值

     alter table test2 add sex enum('w','m') default 'w';
    
  5. null/not null

    欄位在沒有設定not null的時候 預設都為null 此刻插入資料的時候 可以給值 也可以不給值

    如果設定了not null 則必須給值

    alter table test2 add age tinyint unsigned not null;
    insert into test2(username) values('xxx');
    
  6. comment 欄位說明

    欄位說明

     alter table test2 add info varchar(20) comment '個人說明';
    

    表說明

    alter table test2 comment='測試表';
    

null值注意事項

  • null 意味著沒有值或者是未知值
  • 不能對空值進行運算 結果為null
  • 0和null都為假
  • 可以測試是否為空 is null