MySQL 根据第三个字段的值从两个字段中选择一个字段?

mysqlmysqli database

为此,使用 IF()。让我们首先创建一个表 −

mysql> create table DemoTable
   -> (
   -> PlayerName varchar(100),
   -> PlayerScore int,
   -> PlayerStatus varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)

使用 insert 命令在表中插入一些记录 −

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

mysql> insert into DemoTable values('Chris',78,'BAD');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('Robert',90,'BAD');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('David',80,'BAD');
Query OK, 1 row affected (0.23 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+------------+-------------+--------------+
| PlayerName | PlayerScore | PlayerStatus |
+------------+-------------+--------------+
| John       | 88          | BAD          |
| Chris      | 78          | BAD          |
| Robert     | 90          | BAD          |
| David      | 80          | BAD          |
+------------+-------------+--------------+
4 rows in set (0.00 sec)

以下查询根据第三个字段的值从两个字段中选择任意一个字段 −

mysql> select PlayerScore,if(PlayerScore > 80 , PlayerName ,PlayerStatus) AS Result from DemoTable;

输出

+-------------+--------+
| PlayerScore | Result |
+-------------+--------+
|          88 | John   |
|          78 | BAD    |
|          90 | Robert |
|          80 | BAD    |
+-------------+--------+
4 rows in set (0.00 sec)

相关文章