編寫一個單一的 MySQL 查詢,以返回非 NULL 值所在對應行的 ID


讓我們首先建立一個表 -

mysql> create table DemoTable
(
   StudentId int,
   StudentName varchar(100)
);
Query OK, 0 rows affected (0.85 sec)

使用插入命令向表中插入一些記錄 -

mysql> insert into DemoTable values(NULL,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL,'Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(102,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(103,'Sam');
Query OK, 1 row affected (0.18 sec)

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

mysql> select *from DemoTable;

這將產生以下輸出 -

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|      NULL | Chris       |
|      NULL | Robert      |
|       101 | David       |
|       102 | Mike        |
|       103 | Sam         |
+-----------+-------------+
5 rows in set (0.00 sec)

以下是返回非 NULL 值所在對應行的 ID 的查詢 -

mysql> select StudentId from DemoTable where StudentName='David' and StudentId IS NOT NULL;

這將產生以下輸出 -

+-----------+
| StudentId |
+-----------+
|       101 |
+-----------+
1 row in set (0.00 sec)

更新於:2019 年 9 月 26 日

81 次瀏覽

開啟您的職業

完成課程獲得認證

開始
廣告
© . All rights reserved.