【问题标题】:MySQL create temporary table with autoincrement from SELECT onlyMySQL 仅从 SELECT 创建具有自动增量的临时表
【发布时间】:2015-01-03 11:44:37
【问题描述】:

使用 MySQL 我知道可以从 SELECT 创建一个临时表: Create a temporary table in a SELECT statement without a separate CREATE TABLE

我也知道可以在临时表中创建自动增量: Auto Increment in Temporary Table

我想同时做这两个:从 SELECT 语句创建一个临时表,我希望临时表有一个自动增量列。

有可能吗?

【问题讨论】:

  • 谢谢,但我必须从 select 本身创建临时表(之前没有创建临时表)

标签: mysql sql select auto-increment temporary-objects


【解决方案1】:

如果要创建带有行号列的临时表,请使用变量:

create temporary table temp as
    select (@rn := @rn + 1) as seqnum, t.*
    from t cross join
         (select @rn := 0) vars;

对于新的inserts,这不会自动递增。如果需要,您需要更改表定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多