A MySQL table has only 5 fields but hundreds of rows. With good advice (tks Lacoz) I have duplicated the table while ignoring the duplicate rows and now have a new table that does not contain the duplicated rows.
Problem: the new table was inputted in a scrambled order (i.e. when observing the first field, called rel_id). While this doesn’t matter in the real world, at this point it would be helpful to have them in the same order (for referring to past notes, etc).
Example Row: (Note that rel_id is an auto-incrementing, primary key field)
'rel_id' => 1
'host' => 17
'host_type' => 'client'
'rep' => 7
'rep_type => 'cli_mgr'
Here is the method by which user Lacoz assisted me to create the new table, without duplicates:
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");
I tried adding “ORDER BY” to the final query, like this:
mysql_query("insert IGNORE into rels2 select * from rels ORDER BY rel_id");
but it didn’t solve the problem. Rows are still in scrambled order.
First Question: Why did this happen?
Second Question: How could I have ensured that the data was input in the correct order?
Necessary Outcome: For various reasons I really need the data returned to its former appearance (but sans the duplicates). Can someone suggest another approach, even a php script, to accomplish this?
PS: After several google searches I don’t think it’s possible to sort the table’s raw data, only the output. Correct? (It is hard to be sure when a novice to both the concepts and the terminology – we all must start somewhere).
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 BYclause, 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 BYon 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.