Bạn có thể sử dụng NULLIF () từ MySQL để thay thế 0 bằng NULL. Cú pháp như sau -
SELECT *,NULLIF(yourColumnName,0) as anyVariableName from yourTableName;
Để hiểu cú pháp trên, chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau -
mysql> create table Replace0WithNULLDemo -> ( -> Id int NOT NULL auto_increment, -> Name varchar(20), -> Marks int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.53 sec)
Bây giờ bạn có thể chèn một số bản ghi trong bảng bằng cách sử dụng lệnh insert. Truy vấn như sau -
mysql> insert into Replace0WithNULLDemo(Name,Marks) values('John',76); Query OK, 1 row affected (0.16 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Carol',86); Query OK, 1 row affected (0.20 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Sam',0); Query OK, 1 row affected (0.17 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Mike',0); Query OK, 1 row affected (0.16 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Larry',98); Query OK, 1 row affected (0.19 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Bob',0); Query OK, 1 row affected (0.17 sec)
Hiển thị các bản ghi từ bảng bằng cách sử dụng câu lệnh select. Truy vấn như sau -
mysql> select *from Replace0WithNULLDemo;
Sau đây là kết quả -
+----+-------+-------+ | Id | Name | Marks | +----+-------+-------+ | 1 | John | 76 | | 2 | Carol | 86 | | 3 | Sam | 0 | | 4 | Mike | 0 | | 5 | Larry | 98 | | 6 | Bob | 0 | +----+-------+-------+ 6 rows in set (0.00 sec)
Bây giờ chúng ta hãy thay thế 0 bằng NULL. Truy vấn như sau -
mysql> select *,NULLIF(Marks,0) as ReplaceZeroWithNULL from Replace0WithNULLDemo;
Sau đây là đầu ra hiển thị một cột mới, trong đó cột mới đã thay thế 0 bằng NULL -
+----+-------+-------+---------------------+ | Id | Name | Marks | ReplaceZeroWithNULL | +----+-------+-------+---------------------+ | 1 | John | 76 | 76 | | 2 | Carol | 86 | 86 | | 3 | Sam | 0 | NULL | | 4 | Mike | 0 | NULL | | 5 | Larry | 98 | 98 | | 6 | Bob | 0 | NULL | +----+-------+-------+---------------------+ 6 rows in set (0.00 sec)