Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การตรวจสอบว่า Field มี NOT NULL Property ใน MySQL

มี 2 วิธีหลักในการตรวจสอบว่าคอลัมน์มี NOT NULL constraint หรือไม่

วิธีที่ 1: ใช้ DESC (DESCRIBE)

mysql> desc DemoTable;

วิธีที่ 2: ใช้ information_schema.columns

mysql> select column_name, is_nullable 
    from information_schema.columns 
    where table_schema = 'web' 
    and table_name = 'DemoTable';

สร้างตารางตัวอย่าง (มี NOT NULL หลายคอลัมน์)

mysql> create table DemoTable ( 
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    StudentName varchar(40), 
    StudentAge int NOT NULL, 
    IsActiveStudent ENUM('ACTIVE','INACTIVE') NOT NULL, 
    StudentCountryName varchar(40) ); 
Query OK, 0 rows affected (1.53 sec)

ผลลัพธ์ DESC

+--------------------+--------------------------+------+-----+---------+----------------+
| Field              | Type                     | Null | Key | Default | Extra          |
+--------------------+--------------------------+------+-----+---------+----------------+
| StudentId          | int(11)                  | NO   | PRI | NULL    | auto_increment |
| StudentName        | varchar(40)              | YES  |     | NULL    |                |
| StudentAge         | int(11)                  | NO   |     | NULL    |                |
| IsActiveStudent    | enum('ACTIVE','INACTIVE')| NO   |     | NULL    |                |
| StudentCountryName | varchar(40)              | YES  |     | NULL    |                |
+--------------------+--------------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

ผลลัพธ์ information_schema

+--------------------+-------------+
| COLUMN_NAME        | IS_NULLABLE |
+--------------------+-------------+
| StudentId          | NO          |
| StudentName        | YES         |
| StudentAge         | NO          |
| IsActiveStudent    | NO          |
| StudentCountryName | YES         |
+--------------------+-------------+
5 rows in set (0.00 sec)

การอ่านผลลัพธ์

  • Null = NO / IS_NULLABLE = NO = มี NOT NULL constraint
  • Null = YES / IS_NULLABLE = YES = รับ NULL ได้
  • PRIMARY KEY และคอลัมน์ที่มี NOT NULL โดยตรง จะเป็น NO

คิวรี่หาคอลัมน์ที่เป็น NOT NULL ทั้งหมด

SELECT table_name, column_name 
FROM information_schema.columns 
WHERE table_schema = 'web' AND is_nullable = 'NO'
ORDER BY table_name, ordinal_position;

การเพิ่ม/ลบ NOT NULL

-- เพิ่ม NOT NULL (ต้องไม่มีข้อมูล NULL อยู่แล้ว)
ALTER TABLE DemoTable MODIFY StudentName VARCHAR(40) NOT NULL;

-- ลบ NOT NULL
ALTER TABLE DemoTable MODIFY StudentAge INT NULL;