MySQL 查询如何有效选择多行?
你需要使用索引来有效选择多行。我们先创建一个数据表 —
mysql> create table DemoTable1501 -> ( -> Id int NOT NULL PRIMARY KEY, -> URL text -> ); Query OK, 0 rows affected (0.62 sec)
以下是创建索引的查询 —
mysql> create index id_index on DemoTable1501(Id); Query OK, 0 rows affected (0.23 sec) Records: 0 Duplicates: 0 Warnings: 0
使用 insert 命令向数据表中插入一些记录 —
mysql> insert into DemoTable1501 values(101,'www.facebook.com'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1501 values(110,'www.google.com'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1501 values(220,'www.gmail.com'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable1501 values(350,'www.youtube.com'); Query OK, 1 row affected (0.08 sec)
使用 select 语句显示数据表中的所有记录 —
mysql> select * from DemoTable1501;
将产生以下输出 —
+-----+------------------+ | Id | URL | +-----+------------------+ | 101 | www.facebook.com | | 110 | www.google.com | | 220 | www.gmail.com | | 350 | www.youtube.com | +-----+------------------+ 4 rows in set (0.00 sec)
以下是高效选择多行的查询 —
mysql> select * from DemoTable1501 -> where Id in(101,220,350);
将产生以下输出 —
+-----+------------------+ | Id | URL | +-----+------------------+ | 101 | www.facebook.com | | 220 | www.gmail.com | | 350 | www.youtube.com | +-----+------------------+ 3 rows in set (0.00 sec)
为了证明这一点,请使用 Handler_read_key 使用 4 个 ID 中的 3 个的 SHOW 命令 —
mysql> SHOW STATUS LIKE 'Handler_%';
将产生以下输出 —
+----------------------------+-------+ | Variable_name | Value | +----------------------------+-------+ | Handler_commit | 1 | | Handler_delete | 0 | | Handler_discover | 0 | | Handler_external_lock | 2 | | Handler_mrr_init | 0 | | Handler_prepare | 0 | | Handler_read_first | 0 | | Handler_read_key | 3 | | Handler_read_last | 0 | | Handler_read_next | 0 | | Handler_read_prev | 0 | | Handler_read_rnd | 0 | | Handler_read_rnd_next | 0 | | Handler_rollback | 0 | | Handler_savepoint | 0 | | Handler_savepoint_rollback | 0 | | Handler_update | 0 | | Handler_write | 0 | +----------------------------+-------+ 18 rows in set (0.00 sec)
广告