在 MySQL 中為 NOT NULL 值設定 1


為了設定 NOT NULL,使用 IS NOT NULL 並找出該值。語法如下所示 −

select if('' is not NULL,1,0) as anyAliasName;

以下是工作查詢 −

mysql> select if('' is not NULL,1,0);

這將產生以下輸出 −

+------------------------+
| if('' is not NULL,1,0) |
+------------------------+
|                      1 |
+------------------------+
1 row in set (0.00 sec)

為了理解上述語法,讓我們建立一個表 −

mysql> create table DemoTable1915
   (
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用插入命令在表中插入一些記錄 −

mysql> insert into DemoTable1915 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1915 values('');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1915 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1915 values(NULL);
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select * from DemoTable1915;

這將產生以下輸出 −

+-------+
| Name  |
+-------+
| Chris |
|       |
| David |
| NULL  |
+-------+
4 rows in set (0.00 sec)

以下是實現 IF() 併為 NOT NULL 設定 1 的查詢 −

mysql> select if(Name IS NOT NULL,1,0) as Result from DemoTable1915;

這將產生以下輸出 −

+--------+
| Result |
+--------+
|      1 |
|      1 |
|      1 |
|      0 |
+--------+
4 rows in set (0.00 sec)

更新日期:30-Dec-2019

221 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告