2017-02-01 6 views
0

特定の順序でテーブルにデータを挿入したい。これは、各エントリに特定のIDを付ける必要があるためです。私が使用しているのは、選択された声明です:MySQL:select select in order

select (@i := @i + 1) as id, ... 
order by column 

私が抱えている問題は、これは動作していないということです。私は選択クエリから望む結果を得ます。しかし、テーブルにデータを挿入しようとすると、order by文は無視されます。 insert文で正しい順序を強制する方法はありますか?

私がしたいことはこれです:

+----+------+-------------+ 
| id | name | breadcrumbs | 
+----+------+-------------+ 
| 1 | test | 01   | 
| 5 | -d | 01,05  | 
| 4 | c | 04   | 
| 6 | e | 06   | 
| 2 | -a | 06,02  | 
| 3 | --b | 06,02,03 | 
+----+------+-------------+ 

これになるために:別の一時テーブルでは

+----+------+-------------+ 
| id | name | breadcrumbs | 
+----+------+-------------+ 
| 1 | test | 01   | 
| 2 | -d | 01,05  | 
| 3 | c | 04   | 
| 4 | e | 06   | 
| 5 | -a | 06,02  | 
| 6 | --b | 06,02,03 | 
+----+------+-------------+ 

+0

以下の句から選択参照initalisedであることを確信するだろう - など01のための最初の01に続きます02の後に01,02,03が続いて01,03が続いて02が続き、02,01などが続きます。 –

答えて

0

特定の順序でテーブルにデータを挿入したいとします。

MySQLデータベーステーブルのレコードに内部順序はありません。テーブルは、順序付けられていないセットの後にモデル化されます。存在する唯一の順序は、クエリ時にORDER BY句を使用して適用する順序です。レコードが挿入される順序を気にする代わりに、結果セットを必要な順序で並べ替えるのに必要な列とデータがテーブルにあることを確認する必要があります。

1

私は@iはあなたが親にパンくずリストを並べ替えに基づいてIDS、子、孫の基礎を生成したい

MariaDB [sandbox]> drop table if exists t; 
Query OK, 0 rows affected (0.14 sec) 

MariaDB [sandbox]> 
MariaDB [sandbox]> create table t(id int, name varchar(10), breadcrumbs varchar(100)); 
Query OK, 0 rows affected (0.18 sec) 

MariaDB [sandbox]> insert into t values 
    -> ( 1 , 'test' , '01'  ), 
    -> ( 5 , '-d' , '01,05' ), 
    -> ( 4 , 'c' , '04'  ), 
    -> ( 6 , 'e' , '06'  ), 
    -> ( 2 , '-a' , '06,02' ), 
    -> ( 3 , '--b' , '06,02,03'); 
Query OK, 6 rows affected (0.01 sec) 
Records: 6 Duplicates: 0 Warnings: 0 

MariaDB [sandbox]> 
MariaDB [sandbox]> drop table if exists t1; 
Query OK, 0 rows affected (0.13 sec) 

MariaDB [sandbox]> create table t1 as 
    -> select 
    -> @i:[email protected]+1 id, 
    -> t.name,t.breadcrumbs 
    -> from (select @i:=0) i, 
    -> t 
    -> order by breadcrumbs; 
Query OK, 6 rows affected (0.22 sec) 
Records: 6 Duplicates: 0 Warnings: 0 

MariaDB [sandbox]> 
MariaDB [sandbox]> select * from t1; 
+------+------+-------------+ 
| id | name | breadcrumbs | 
+------+------+-------------+ 
| 1 | test | 01   | 
| 2 | -d | 01,05  | 
| 3 | c | 04   | 
| 4 | e | 06   | 
| 5 | -a | 06,02  | 
| 6 | --b | 06,02,03 | 
+------+------+-------------+ 
6 rows in set (0.00 sec) 
+0

トリックと同じように、insertをcreate tableに置き換えます。 – user110971