2017-02-01 51 views
0

我想按特定顺序将数据插入表中。这是因为我需要给每个条目一个特定的ID。我正在使用的是一个选择声明:MySQL:按顺序插入选择

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

我遇到的问题是,这似乎并不奏效。我从选择查询中得到我想要的结果。但是,当我尝试将数据插入到表中时,按语句顺序将被忽略。有没有办法强制插入语句中的正确顺序?

我想是这样的:

+----+------+-------------+ 
| 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

你要基于排序在父母,子女面包屑IDS,孙子基础上选择 - 例如01首,然后01, 02,01,02,03,01,03,02,02,01等等? –

回答

0

我想按特定的顺序在表中插入数据。

MySQL数据库表中没有记录的内部命令。表格是在无序集合之后建模的。唯一存在的顺序是您在查询时使用ORDER BY子句应用的顺序。因此,向前推进,而不是担心插入记录的顺序,您应该确保您的表具有必要的列和数据,以便按照您的要求对结果集进行排序。

1

我会做出一定的@i是initalised看到以下条款

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

替换插入与创建表的做法。 – user110971