Computer >> Máy Tính >  >> Lập trình >> MySQL

Viết một truy vấn MySQL duy nhất để trả về ID từ hàng tương ứng là giá trị NOT NULL

Đầu tiên chúng ta hãy tạo một bảng -

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

Chèn một số bản ghi vào bảng bằng lệnh chèn -

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)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable;

Điều này sẽ tạo ra kết quả sau -

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

Sau đây là truy vấn trả về ID từ hàng tương ứng là giá trị KHÔNG ĐẦY ĐỦ -

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

Điều này sẽ tạo ra kết quả sau -

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