MySQL:按顺序插入选择

标签 mysql sql-order-by sql-insert

我想按特定顺序将数据插入表中。这是因为我需要为每个条目指定一个特定的 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 已初始化,请参阅下面的 select in from 子句

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:按顺序插入选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978038/

相关文章:

mysql - 向数据库插入一条sql语句

php - 在表中显示数据的最佳方式

php - 自动计算mysql表中的数据

php - 按日期时间显示来自多个表的数据

php - MySQL从其他表插入数据

SQL Server 查询进行空控制

mysql - 自动增量非唯一列

PHP/MYSQL - 通过 as php 变量进行 mysql 查询相关的语法错误

sql - Oracle Insert Select with order by

sql - 使用 PostgreSQL 进行字母数字排序