帶 OR 和 AND 條件的 MySQL 查詢


我們首先建立一個表格 -

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.63 sec)

使用 insert 命令在表格中插入一些記錄 -

mysql> insert into DemoTable(Name,Age) values('John',21);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name,Age) values(Null,20);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Name,Age) values('David',23);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name,Age) values('Carol',null);
Query OK, 1 row affected (0.17 sec)

使用 select 語句顯示錶格中的所有記錄 -

mysql> select *from DemoTable;

輸出

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | John  | 21   |
| 2  | NULL  | 20   |
| 3  | David | 23   |
| 4  | Carol | NULL |
+----+-------+------+
4 rows in set (0.00 sec)

以下是帶 OR 和 AND 條件的查詢 -

mysql> select *from DemoTable -> where Name='David' OR (Name is null AND Age=20);

輸出

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 2  | NULL  | 20   |
| 3  | David | 23   |
+----+-------+------+
2 rows in set (0.00 sec)

更新於:2019 年 7 月 30 日

132 次瀏覽

開啟您的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.