MYSQL,PHP,按不工作顺序,主键

时间:2016-09-04 16:33:49

标签: mysql sql-order-by

我正在从PHP生成mySQL查询。

部分查询根据某些变量(不包括主键)重新排序表。

代码不会产生错误,但表格没有排序。

我回复了SQL代码,它看起来是正确的,我尝试直接在phpMyAdmin中运行它,它也运行没有错误,但表仍未按要求排序。

alter table anavar order by dset_name, var_id;

我很确定这与我有一个排序中不存在的主键变量(UID)这一事实有关。

在运行查询之前和之后,表仍由UID排序。删除UID并重新运行查询会产生一个正确排序的表,但这似乎是一个过度的解决方案。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

create table t2
(   id int auto_increment primary key,
    someInt int not null,
    thing varchar(100) not null,
    theWhen datetime not null,
    key(theWhen) -- creates an index on theWhen
);
-- my table now has 2 indexes on it 
-- see it by running `show indexes from t2`

-- truncate table t2;
insert t2(someInt,thing,theWhen) values
(17,'chopstick','2016-05-08 13:00:00'),
(14,'alligator','2016-05-01'),
(11,'snail','2016-07-08 19:00:00');

select * from t2; -- returns in physical order (the primary key `id`)
select * from t2 order by thing; -- returns via thing, which has no index anyway
select * from t2 order by theWhen,thing; -- partial index use

note that indexes aren't even used until you have a significant number of rows in a db anyway

编辑(新数据进入)

insert t2 (someInt,thing,theWhen) values (777,'apple',now());

select t2.id,t2.thing,t2.theWhen,@rnk:=@rnk+1 as rank  
from t2 
cross join (select @rnk:=0) xParams 
order by thing; 
+----+-----------+---------------------+------+
| id | thing     | theWhen             | rank |
+----+-----------+---------------------+------+
|  2 | alligator | 2016-05-01 00:00:00 |    1 |
|  4 | apple     | 2016-09-04 15:04:50 |    2 |
|  1 | chopstick | 2016-05-08 13:00:00 |    3 |
|  3 | snail     | 2016-07-08 19:00:00 |    4 |
+----+-----------+---------------------+------+

专注于您可以随时维护辅助索引并生成rank这一事实。