iT邦幫忙

DAY 7
7

MySQL那些事兒系列 第 7

MySQL的特殊指令HANDLER

HANDLER 是一個很有趣的指令,可以讓我們一列列的瀏覽資料.
先來建立測試Table.

CREATE TABLE ithelp1007a(
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
class CHAR(1) NOT NULL,
name CHAR(20) NOT NULL,
score TINYINT UNSIGNED NOT NULL
);

INSERT INTO ithelp1007a(class, name, score) VALUES
('A', 'Tom', 78),
('A', 'Mary', 25),
('A', 'John', 65),
('B', 'Hitomi', 95),
('B', 'Asami', 84),
('B', 'Keiko', 73);

首先打開 HANDLER
asami@[akina]>HANDLER ithelp1007a OPEN;
Query OK, 0 rows affected (0.00 sec)

讀取第一筆
asami@[akina]>HANDLER ithelp1007a READ FIRST;
+----+-------+------+-------+
| id | class | name | score |
+----+-------+------+-------+
|  1 | A     | Tom  |    78 |
+----+-------+------+-------+
1 row in set (0.00 sec)

讀取下一筆
asami@[akina]>HANDLER ithelp1007a READ NEXT;
+----+-------+------+-------+
| id | class | name | score |
+----+-------+------+-------+
|  2 | A     | Mary |    25 |
+----+-------+------+-------+
1 row in set (0.00 sec)

關閉HANDLER
asami@[akina]>HANDLER ithelp1007a CLOSE;
Query OK, 0 rows affected (0.00 sec)

以主鍵為補助方式瀏覽

HANDLER ithelp1007a OPEN AS H;

第一筆
asami@[akina]>HANDLER H READ `PRIMARY` FIRST;
+----+-------+------+-------+
| id | class | name | score |
+----+-------+------+-------+
|  1 | A     | Tom  |    78 |
+----+-------+------+-------+
1 row in set (0.00 sec)

最後一筆
asami@[akina]>HANDLER H READ `PRIMARY` LAST;
+----+-------+-------+-------+
| id | class | name  | score |
+----+-------+-------+-------+
|  6 | B     | Keiko |    73 |
+----+-------+-------+-------+
1 row in set (0.00 sec)

從最後一筆往前一筆
asami@[akina]>HANDLER H READ `PRIMARY` PREV;
+----+-------+-------+-------+
| id | class | name  | score |
+----+-------+-------+-------+
|  5 | B     | Asami |    84 |
+----+-------+-------+-------+
1 row in set (0.00 sec)

關閉HANDLER


若要以分數score為順序來瀏覽時,我們必須要建立
以score為key的INDEX.

asami@[akina]>CREATE INDEX SCORE ON ithelp1007a(score);
Query OK, 0 rows affected (0.29 sec)
Records: 0  Duplicates: 0  Warnings: 0

一樣OPEN HANDLER

asami@[akina]>HANDLER ithelp1007a OPEN AS `S`;
Query OK, 0 rows affected (0.00 sec)

asami@[akina]>HANDLER S READ SCORE FIRST;
+----+-------+------+-------+
| id | class | name | score |
+----+-------+------+-------+
|  2 | A     | Mary |    25 |
+----+-------+------+-------+
1 row in set (0.00 sec)

因為剛剛建立INDEX 時是升冪排列,所以會從分數最低的開始.

INDEX也可以用組合的KEY,例如class,score 的組合,
以及降冪的情況,可以自行視需要建立,依序存取.

HANDLER也可以加上 LIMIT, 來取出多筆.
或是使用條件,例如找出84分的.

asami@[akina]>HANDLER S READ SCORE=(84);
+----+-------+-------+-------+
| id | class | name  | score |
+----+-------+-------+-------+
|  5 | B     | Asami |    84 |
+----+-------+-------+-------+
1 row in set (0.00 sec)

在有些情況下,可以使用HANDLER 來展示資料.


上一篇
SQL Query 執行的細節的改進查詢方法
下一篇
SQL MERGE 指令在MySQL的實作
系列文
MySQL那些事兒30

2 則留言

0
SunAllen
iT邦高手 1 級 ‧ 2013-10-07 15:55:05

沙發 好讚! 謝謝小雨大分享

魯大 iT邦高手 1 級 ‧ 2013-10-07 16:52:28 檢舉

沙發
坐過去一點,擠一下..

鐵殼心 iT邦高手 1 級 ‧ 2013-10-07 17:40:34 檢舉

坐過去一點, 沒有位置了.

我要留言

立即登入留言