【问题标题】:Insert into select and update in single query在单个查询中插入选择和更新
【发布时间】:2010-05-26 20:06:44
【问题描述】:
I have 4 tables: tempTBL, linksTBL and categoryTBL, extra

在我的 tempTBL 上,我有:ID、名称、url、cat、isinserted 列 在我的链接TBL 我有:ID、名称、别名列 在我的 categoryTBL 上,我有:cl_id、link_id、cat_id 在我的 extraTBL 上,我有:id、link_id、值

如何执行单个查询以从 tempTBL 中选择 isinsrted = 0 的所有项目,然后将它们插入到 linksTBL 中,对于插入的每条记录,拾取 ID(这是主要的),然后将该 ID 插入到 cat_id = 88 的 categoryTBL 中。之后为 link_id 插入 extraTBL ID,为 value 插入 url。

我知道这很令人困惑,无论如何我都会发布这个......

这是我目前所拥有的:

INSERT IGNORE INTO linksTBL (link_id,link_name,alias)
VALUES(NULL,'tex2','hello');         # generate ID by inserting NULL

INSERT INTO categoryTBL (link_id,cat_id) 值(LAST_INSERT_ID(),'88'); # 在第二个表中使用 ID

我想在这里添加它只选择 isinserted = 0 的项目并插入那些记录,并且一旦插入,就会将 isinserted 更改为 1,因此下次运行时,它不会再次添加它们。

【问题讨论】:

    标签: sql mysql


    【解决方案1】:

    正如 longneck 所说,你不能在一个查询中做多件事,但你可以在一个存储过程中。

    【讨论】:

    • 这是不正确的。请在此处查看有关 INSERT ... SELECT 的 mysql 文档:dev.mysql.com/doc/refman/5.1/en/insert-select.html
    • 这不是错误的。您可以从一个选择中插入(1 件事),但不能执行 2 次插入(2 件事)。
    【解决方案2】:

    http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

    INSERT INTO linksTBL (link_id,link_name,alias)
        SELECT field1, field2, field3
            FROM othertable
        WHERE inserted=0;
    

    【讨论】:

      【解决方案3】:

      这在单个查询中是不可能的。您必须插入行,然后运行单独的更新语句。

      【讨论】:

      • @KevinPeno - 这需要来自其他表的数据,如果我有新数据,我基本上想要更新一行,如果它已经基于键,否则插入它
      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 2014-09-01
      • 2013-11-20
      • 2016-01-16
      相关资源
      最近更新 更多