编写一个单一的 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)
广告