InnoDB テーブルを使用する場合、それらは常に主キーの順序で格納されます。したがって、SELECT
other を指定せずにテーブルから取得するORDER BY
と、その順序で行が表示されます。
エラー コード: 1075 テーブル定義が正しくありません。自動列は 1 つしか存在できず、キーとして定義する必要があります ==> 主キーを削除できないのはなぜですか? – ダミアン
InnoDB では、AUTO_INCREMENT カラムがある場合、それがインデックスの最初のカラムである必要があります。通常、主キー インデックスとして定義しますが、主キーを削除する場合は、少なくとも別のインデックスを定義する必要があります。
例: 自動インクリメント主キーを持つテスト テーブルを作成します。
mysql> create table record_table (id int auto_increment primary key);
mysql> insert into record_table values (1), (2), (3);
キーの一部ではない自動インクリメント列を持つことはできません。
mysql> alter table record_table drop primary key;
ERROR 1075 (42000): Incorrect table definition;
there can be only one auto column and it must be defined as a key
プライマリ キーを削除して、同じ列にセカンダリ キーを追加すると、これは InnoDB を満たします。
mysql> alter table record_table drop primary key, add key (id);
Query OK, 3 rows affected (0.13 sec)
しかし、その列にキーを持たないようにしようとすると、それもエラーになります。
mysql> alter table record_table drop key id;
ERROR 1075 (42000): Incorrect table definition;
there can be only one auto column and it must be defined as a key
回避策の 1 つは、テーブルに追加の列を作成し、それにランダムな値を割り当てることです。その後、その列を ORDER BY できます。
mysql> alter table record_table add column sort float;
mysql> update record_table set sort = rand();
mysql> select * from record_table ;
+----+----------+
| id | sort |
+----+----------+
| 1 | 0.439593 |
| 2 | 0.416936 |
| 3 | 0.7659 |
+----+----------+
mysql> select * from record_table order by sort;
+----+----------+
| id | sort |
+----+----------+
| 2 | 0.416936 |
| 1 | 0.439593 |
| 3 | 0.7659 |
+----+----------+
ランダムな値を更新するだけで、データを前後にコピーすることなくテーブルを「再シャッフル」できます。
mysql> update record_table set sort = rand();
mysql> select * from record_table order by sort;
+----+----------+
| id | sort |
+----+----------+
| 1 | 0.137319 |
| 3 | 0.329505 |
| 2 | 0.348292 |
+----+----------+