帶 OR 的 MySQL SELECT IF 語句?


你可以將 SELECT IF 語句與 OR 一起使用。要了解帶有 OR 的 select 語句,讓我們建立一個表。建立表的查詢如下 −

mysql> create table EmployeeInformation
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(100),
   -> EmployeeStatus varchar(100)
   -> );
Query OK, 0 rows affected (0.68 sec)

使用 insert 命令向表中插入一些記錄。查詢如下 −

mysql> insert into EmployeeInformation values(1,'Sam','FullTime');
Query OK, 1 row affected (0.23 sec)

mysql> insert into EmployeeInformation values(2,'Mike','PartTime');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EmployeeInformation values(3,'Bob','Intern');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EmployeeInformation values(4,'Carol','FullTime');
Query OK, 1 row affected (0.16 sec)

mysql> insert into EmployeeInformation values(5,'John','FullTime');
Query OK, 1 row affected (0.19 sec)

mysql> insert into EmployeeInformation values(6,'Johnson','PartTime');
Query OK, 1 row affected (0.19 sec)

mysql> insert into EmployeeInformation values(7,'Maria','Intern');
Query OK, 1 row affected (0.12 sec)

現在讓我們使用 select 命令顯示錶中的所有記錄。查詢如下 −

mysql> select *from EmployeeInformation;

輸出

+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeStatus |
+------------+--------------+----------------+
|          1 | Sam          | FullTime       |
|          2 | Mike         | PartTime       |
|          3 | Bob          | Intern         |
|          4 | Carol        | FullTime       |
|          5 | John         | FullTime       |
|          6 | Johnson      | PartTime       |
|          7 | Maria        | Intern         |
+------------+--------------+----------------+
7 rows in set (0.00 sec)

以下是執行帶有 OR 的 SELECT IF 語句的查詢。在下面的查詢中,你將只獲得帶有員工狀態 FullTime 和 Intern 的 EmployeeName,否則你將獲得員工的狀態。

查詢如下 −

mysql> select if(EmployeeStatus='FullTime' or
EmployeeStatus='Intern',EmployeeName,EmployeeStatus) as Status from
EmployeeInformation;

輸出

+----------+
| Status   |
+----------+
| Sam      |
| PartTime |
| Bob      |
| Carol    |
| John     |
| PartTime |
| Maria    |
+----------+
7 rows in set (0.00 sec)

更新時間:30-Jul-2019

929 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告