Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

NULL 값으로 정렬하는 MySQL 쿼리

<시간/>

먼저 테이블을 생성하겠습니다 -

mysql> create table DemoTable707 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(100),
   StudentMarks int
);
Query OK, 0 rows affected (0.59 sec)

삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -

mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('John',45);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values(NULL,65);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('Chris',78);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values(NULL,89);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('Robert',99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values(NULL,34);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('Mike',43);
Query OK, 1 row affected (0.20 sec)

select 문을 사용하여 테이블의 모든 레코드 표시 -

mysql> select *from DemoTable707;

그러면 다음과 같은 출력이 생성됩니다. -

+-----------+------------------+--------------+
| StudentId | StudentFirstName | StudentMarks |
+-----------+------------------+--------------+
| 1         | John             | 45           |
| 2         | NULL             | 65           |
| 3         | Chris            | 78           |
| 4         | NULL             | 89           |
| 5         | Robert           | 99           |
| 6         | NULL             | 34           |
| 7         | Mike             | 43            |
+-----------+------------------+--------------+
7 rows in set (0.00 sec)

다음은 NULL 값으로 정렬하는 쿼리입니다 -

mysql> select *from DemoTable707 order by StudentFirstName IS NULL, StudentFirstName DESC;

그러면 다음과 같은 출력이 생성됩니다. -

+-----------+------------------+--------------+
| StudentId | StudentFirstName | StudentMarks |
+-----------+------------------+--------------+
| 5         | Robert           | 99           |
| 7         | Mike             | 43           |
| 1         | John             | 45           |
| 3         | Chris            | 78           |
| 2         | NULL             | 65           |
| 4         | NULL             | 89           |
| 6         | NULL             | 34           |
+-----------+------------------+--------------+
7 rows in set (0.00 sec)