繁体   English   中英

MySQL:按顺序插入选择

[英]MySQL: insert select in order

我想按特定顺序将数据插入表中。 这是因为我需要为每个条目指定一个特定的ID。 我正在使用的是一条select语句:

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

我遇到的问题是,这似乎不起作用。 我从选择查询中得到了想要的结果。 但是,当我尝试将数据插入表中时,order by语句将被忽略。 有什么方法可以在插入语句中强制正确的顺序吗?

我想要的是:

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

在单独的临时表中。

我可以确定@i是大写的,请参见下面的from子句中的select

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:=@i+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)

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

MySQL数据库表中的记录没有内部顺序。 表是按照无序集建模的。 存在的唯一顺序是查询时通过使用ORDER BY子句应用的顺序。 因此,继续前进,不必担心记录的插入顺序,而应确保表具有必要的列和数据,以便按所需方式对结果集进行排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM