MySQL 查詢中查詢表中備選記錄


要從一張表中查詢備選記錄,你需要使用 OR 條件,如下面的語法所示 −

select *from yourTableName where yourColumnName=yourValue1 OR yourColumnName=yourValue2…...N;

讓我們首先建立一個表 −

mysql> create table DemoTable772 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100),
   Age int
);
Query OK, 0 rows affected (0.76 sec)

對錶插入一些記錄,使用插入命令 −

mysql> insert into DemoTable772(Name,Age) values('Chris',21);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable772(Name,Age) values('Robert',26);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable772(Name,Age) values('Mike',27);
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable772(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.45 sec)
mysql> insert into DemoTable772(Name,Age) values('Carol',28);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable772(Name,Age) values('David',25);
Query OK, 1 row affected (0.93 sec)

使用選擇語句顯示錶中的所有記錄 −

mysql> select *from DemoTable772;

將產生以下輸出 -

+----+--------+------+
| Id | Name   | Age  |
+----+--------+------+
|  1 | Chris  | 21   |
|  2 | Robert | 26   |
|  3 | Mike   | 27   |
|  4 | Sam    | 24   |
|  5 | Carol  | 28   |
|  6 | David  | 25   |
+----+--------+------+
6 rows in set (0.00 sec)

以下是 MySQL OR 查詢 −

mysql> select *from DemoTable772 where Id=2 OR Id=4 OR Id=6;

將產生以下輸出 -

+----+--------+------+
| Id | Name   | Age  |
+----+--------+------+
|  2 | Robert | 26   |
|  4 | Sam    | 24   |
|  6 | David  | 25   |
+----+--------+------+
3 rows in set (0.01 sec)

更新日期: 03-9 月-2019

228 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.