【问题标题】:SELECT * INTO with a subquery [duplicate]带有子查询的 SELECT * INTO [重复]
【发布时间】:2019-01-02 02:46:51
【问题描述】:

我是 MySQL 的新手,我正在尝试使用 select * into 创建一个表。我的问题是我正在使用子查询,但我不了解查询的正确语法。 Morover,通过这个查询,我将显示我要复制的所有记录:

    select trasco_titolarita.* 
    from trasco_titolarita
    inner join (
                select max(id) as maxID, soggetto_id 
                from trasco_titolarita group by soggetto_id
               ) maxID
    on maxID.maxID = trasco_titolarita.id

如上所述,此查询显示了我感兴趣的所有记录。我想要实现的目标是将所有这些记录复制到另一个新表中,所以我尝试这样做:

select * into newtable from
(
select trasco_titolarita.* 
from trasco_titolarita
    inner join (
                select max(id) as maxID, soggetto_id 
                from trasco_titolarita group by soggetto_id
               ) maxID
    on maxID.maxID = trasco_titolarita.id

)

但这实际上不起作用,因为我认为子查询中的第一个选择只是一个显示。我得到的错误是“')'附近的语法不正确” 有人可以给我一些建议吗?

【问题讨论】:

  • 尝试列出所有字段而不是 * 并在内部查询中列出它们。

标签: mysql


【解决方案1】:

您需要将select * into 更改为insert intohttps://dev.mysql.com/doc/refman/8.0/en/insert-select.html

假设newtable 具有与现有trasco_titolarita 相似的列。 适合您的查询是 ::

insert into newtable
select trasco_titolarita.* 
from trasco_titolarita
    inner join (
                select max(id) as maxID, soggetto_id 
                from trasco_titolarita group by soggetto_id
               ) maxID
    on maxID.maxID = trasco_titolarita.id

【讨论】:

  • 如此明显的编辑。我完全专注于 select into,因为我几乎用它来复制 tmp_tables 中的原始表。谢谢!
  • 你可以accept answers that solve your problem - 它会帮助其他人寻找答案。 :)
  • SELECT INTO newtable 创建表,INSERT INTO newtable 要求表已经存在。
【解决方案2】:

我很确定 MySQL 服务器不支持 SELECT ... INTO 语法

您可以改为使用 CREATE TABLE new_tbl SELECT * FROM orig_tbl WHERE .... 语法

更多信息请阅读 https://dev.mysql.com/doc/refman/8.0/en/ansi-diff-select-into-table.html

【讨论】:

  • 我确实支持 select ... into ... 语法,但该语法在 MySQL 中有不同的用途。您可以使用该语法将数据导出到文件或将数据提取到变量中。
猜你喜欢
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2020-03-16
  • 2018-09-16
相关资源
最近更新 更多