Mysql中的 not null

創建醫生信息表 doctor_info1 、doctor_info2 ,區別是 doctor_info1 中doctor_name 加上not null 約束

CREATE TABLE `doctor_info1` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `doctor_name` varchar(32) NOT NULL,
  `doctor_code` varchar(32) DEFAULT NULL,
  `dept_code` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='醫生信息表';



CREATE TABLE `doctor_info2` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `doctor_name` varchar(32) DEFAULT NULL,
  `doctor_code` varchar(32) DEFAULT NULL,
  `dept_code` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='醫生信息表';

不使用Null 的好處

1、NOT IN、!= 等負向條件查詢在有 NULL 值的情況下返回非空行的結果集,查詢容易出錯
比如上例中的 doctor_info2,執行如下 SQL 語句。

SELECT * FROM doctor_info2 WHERE doctor_name != '王平'

預期返回除了 doctor_name = '王平' 的結果,結果id爲7的未查出。
 

2、單列索引不存null值,複合索引不存全爲null的值,如果列允許爲null,可能會得到 不符合預期的結果集

3、如果兩個字段進行拼接:比如 doctor_code + dept_code,首先要各字段進行非null判斷,否則只要有任意一個字段爲空都會導致拼接的結果爲null。比如使用 concat 函數拼接時同理。

4、如果有 Null column 存在的情況下,count(Null column)需要格外注意,null 值不會參與統計.

     注意 Null 字段的判斷方式, = null 將會得到錯誤的結果(用is null 、is not null 來判斷)。

5、Null 列需要更多的存儲空間:需要一個額外字節作爲判斷是否爲 NULL 的標誌位。

 

Mysql 中設置 not null 和 DEFAULT 約束 對象入參爲null的情況:

1. 在代碼中給對象設置默認值

2. 手寫sql  insert 語句,對象中爲null 不需要入庫的字段 不在sql中插入

<insert id="insertByBatch" parameterType = "java.util.List" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO fms_order_statement
        (statement_batch_number, batch_type, batch_type_name,
         store_name, store_type_name, area_name, statement_date)
        VALUES
        <foreach collection="list" index="index" item="item" separator=",">
            (#{item.statementBatchNumber}, #{item.batchType},#{item.batchTypeName},
             #{item.storeName},#{item.storeTypeName},#{item.areaName},#item.statementDate})
        </foreach>
    </insert>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章