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

MySQL 문에서 IF ELSE 문?

<시간/>

If-Else 문에서 조건은 값에 따라 true 또는 false로 평가됩니다.

예를 들어 보겠습니다. 먼저 테이블을 생성하겠습니다. CREATE 명령은 테이블을 생성하는 데 사용됩니다.

mysql> create table IfelseDemo
   - > (
   - > id int,
   - > FirstName varchar(100)
   - > );
Query OK, 0 rows affected (0.46 sec)

레코드는 INSERT 명령을 사용하여 삽입됩니다.

mysql> insert into IfelseDemo values(1,'John');
Query OK, 1 row affected (0.13 sec)

mysql>  insert into IfelseDemo values(2,'Carol');
Query OK, 1 row affected (0.31 sec)

mysql>  insert into IfelseDemo values(3,'John');
Query OK, 1 row affected (0.11 sec)

mysql>  insert into IfelseDemo values(4,'Carol');
Query OK, 1 row affected (0.14 sec)

mysql>  insert into IfelseDemo values(5,'John');
Query OK, 1 row affected (0.11 sec)

모든 기록을 표시합니다.

mysql> select *from IfelseDemo;

다음은 결과입니다.

+------+-----------+
| id   | FirstName |
+------+-----------+
|    1 | John      |
|    2 | Carol     |
|    3 | John      |
|    4 | Carol     |
|    5 | John      |
+------+-----------+
5 rows in set (0.00 sec)

다음은 if-else 문을 사용하는 쿼리입니다.

mysql> SELECT id, FirstName, (case when (id = 2 and FirstName = 'Carol')
   - > then
   - > 'Welcome Carol'
   - > else
   - > 'You are not Carol with id 2'
   - >end)as Message from IfelseDemo;

다음은 출력입니다.

+------+-----------+-----------------------------+
| id   | FirstName | Message                     |
+------+-----------+-----------------------------+
|    1 | John      | You are not Carol with id 2 |
|    2 | Carol     | Welcome Carol               |
|    3 | John      | You are not Carol with id 2 |
|    4 | Carol     | You are not Carol with id 2 |
|    5 | john      | You are not Carol with id 2 |
+------+-----------+-----------------------------+
5 rows in set (0.00 sec)