有个问题小弟想请教一下,mysql默认查询规则是什么?默认的查询是不是有默认的排序方式?
举个例子:
一个表table, abcid为主键,按照1开始自增,还有一些其它的字段,如name,money等;
select的时候例如:select * from user where money = 100;
查询结果按照abcid顺序排列。
再查一条select * from user where money = 1000;
查询结果可能就按照abcid逆序排序。很不解,为什么查询结果会不稳定?
举个例子:
一个表table, abcid为主键,按照1开始自增,还有一些其它的字段,如name,money等;
select的时候例如:select * from user where money = 100;
查询结果按照abcid顺序排列。
再查一条select * from user where money = 1000;
查询结果可能就按照abcid逆序排序。很不解,为什么查询结果会不稳定?
在数据库中没有顺序的概念,先进则在前面,排序是逻辑上的顺序。
有可能没有用到abcid索引,EXPLAIN SQL语句,贴结果
如果没有指定ORDER BY,应该是按照物理顺序,即先进入表中的字段位置在前。
最好EXPLAIN一下
explain的结果如下:
select_type table type key key_len ref rows
SIMPLE abc ref abcid 4 const 307
来测试一下,用WINRAR压缩
-> id int primary key,
-> col int
-> )engine=myisam;
Query OK, 0 rows affected (0.05 sec)mysql> insert into tx values
-> (1 ,1),
-> (2 ,1),
-> (3 ,1),
-> (7 ,2),
-> (6 ,2),
-> (5 ,2),
-> (4 ,2),
-> (8 ,3),
-> (11 ,3),
-> (10 ,3),
-> (9 ,3);
Query OK, 11 rows affected (0.00 sec)
Records: 11 Duplicates: 0 Warnings:-- 物理顺序
mysql> select * from tx;
+----+------+
| id | col |
+----+------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 7 | 2 |
| 6 | 2 |
| 5 | 2 |
| 4 | 2 |
| 8 | 3 |
| 11 | 3 |
| 10 | 3 |
| 9 | 3 |
+----+------+
11 rows in set (0.00 sec)
-- 物理顺序
mysql> select id from tx where col=3;
+----+
| id |
+----+
| 8 |
| 11 |
| 10 |
| 9 |
+----+
4 rows in set (0.00 sec)
-- 主键顺序
mysql> select id from tx;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
+----+
11 rows in set (0.00 sec)mysql> create index tx_col on tx(col,id);
Query OK, 11 rows affected (0.08 sec)
Records: 11 Duplicates: 0 Warnings: 0-- 加索引后为索引顺序
mysql> select * from tx where col=3;
+----+------+
| id | col |
+----+------+
| 8 | 3 |
| 9 | 3 |
| 10 | 3 |
| 11 | 3 |
+----+------+
4 rows in set (0.02 sec)mysql>
到www.eluyouni.com
帮你解决疑问
寻找幸福