MySQL 多列篩選?


要按多列執行篩選,請連同 OR 使用 where 子句。我們先建立一個表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(10),
   Score int
   );
Query OK, 0 rows affected (0.28 sec)

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

mysql> insert into DemoTable(Name,Score) values('John',80);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Name,Score) values('John',90);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name,Score) values('Carol',89);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Name,Score) values('John',86);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Name,Score) values('Carol',98);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name,Score) values('David',99);
Query OK, 1 row affected (0.06 sec)

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

mysql> select *from DemoTable;

將會生成以下輸出 −

+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
| 1  | John  | 80    |
| 2  | John  | 90    |
| 3  | Carol | 89    |
| 4  | John  | 86    |
| 5  | Carol | 98    |
| 6  | David | 99    |
+----+-------+-------+
6 rows in set (0.00 sec)

以下是按多列執行篩選的查詢 −

mysql> select *from DemoTable where (Name,Score)=('John', 90) or (Name,Score)=('Carol', 98);

將會生成以下輸出 −

+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
| 2  | John  | 90    |
| 5  | Carol | 98    |
+----+-------+-------+
2 rows in set (0.00 sec)

更新於: 30-Jul-2019

2 千次 + 瀏覽

開啟你的 職業

透過完成課程認證

開始
廣告