0

MySQL 表只有 5 个字段,但有数百行。有了好的建议(tks Lacoz),我在忽略重复行的同时复制了表,现在有一个不包含重复行的新表。

问题:新表是以打乱的顺序输入的(即在观察第一个字段时,称为rel_id)。虽然这在现实世界中并不重要,但此时将它们按相同的顺序排列会很有帮助(用于引用过去的笔记等)。

示例行:(请注意,这rel_id是一个自动递增的主键字段)

'rel_id' => 1
'host' => 17
'host_type' => 'client'
'rep' => 7
'rep_type => 'cli_mgr'

这是用户 Lacoz 帮助我创建新表的方法,没有重复:

mysql_query("create table rels2 like rels");
mysql_query("alter table rels2 add unique index(host,host_type,rep,rep_type)");
mysql_query("insert IGNORE into rels2 select * from rels");

我尝试在最终查询中添加“ORDER BY”,如下所示:

mysql_query("insert IGNORE into rels2 select * from rels ORDER BY rel_id");

但它并没有解决问题。行仍然是乱序的。

第一个问题:为什么会这样?

第二个问题:我如何确保数据以正确的顺序输入?

必要的结果:由于各种原因,我真的需要将数据恢复到原来的样子(但没有重复)。有人可以建议另一种方法,甚至是 php 脚本来完成此任务吗?

PS:经过几次谷歌搜索后,我认为无法对表格的原始数据进行排序,只能对输出进行排序。正确的?(很难确定什么时候是概念和术语的新手——我们都必须从某个地方开始)。

4

2 回答 2

1

Conceptually, data in a relational database is not stored in any particular order. Mathematically, it's a set or relations, and sets have no ordering. That's why SQL doesn't provide any way to insert rows in a certain sequence (e.g. insert this row at the end, at the beginning, after some other row, etc...). It only provides a way to filter the output of a query given some specified ordering criteria.

Of course, a concrete implementation of SQL has to ultimately store things on disk in some kind of order, which is why you notice a repeatable ordering when you query a table without giving an ORDER BY clause, but you can't count on it. Your software should assume that rows will come out in arbitrary order.

If you need results to come out in a particular order, use ORDER BY on the query. Maybe build an appropriate index (if there isn't one already) to make sure the database can produce the ordering you request with good performance.

于 2012-11-07T20:41:55.647 回答
0

当您通过添加唯一索引设法解决重复时,如果您希望它们是 auto_increment,则必须加载新的主键值。所以建议的查询是这样的

mysql_query("insert IGNORE into rels2(host,host_type,rep,rep_type) select host,host_type,rep,rep_type from rels ORDER BY rel_id");

祝你好运!

于 2012-11-07T21:04:49.513 回答