【问题标题】:mysql modify select result with insertmysql用插入修改选择结果
【发布时间】:2014-08-01 13:23:25
【问题描述】:

我正在使用insert into table2 select from table1 声明。

table2 的字段比table1 多。除了选择结果中的值之外,我如何使用其他值填充额外的字段。

table1col1, col2, col3 table2 has col1, col2, col3, col4, col5, col6

table2 中的 col4 和 col5 将使用 col2 和 col3 中的修改值。

示例:

tabl1.col2 的值为 tag 6512tabl1.col3 的值为 bin location

table2 中的col4 将使用 table1.col3 中的部分值 bin 和 table1.col2 中的“6512”
所以table2.col4 将是bin 6512

sql:

insert into table2(col1, col2, col3, col4, col5) select * from table1 (and add values for col4 and col5) 

感谢任何帮助。

【问题讨论】:

  • 似乎(至少在我看来!)在运行插入之前操作 select 语句的结果是最简单的

标签: php sql mysqli-multi-query


【解决方案1】:

好吧,我认为答案可以分为两部分。

  1. 如何在我的子选择中生成 2 个额外的列。
  2. 如何操作table1之前的某些列中的数据 我将上述操作的结果放入table2

第 1 点:

在您的子选择中,您可以像这样简单地生成 3 个额外的列。

INSERT INTO table2 (col1, col2, col3, col4, col5) 
            SELECT *, 'dummy1', 'dummy2' FROM table1

这当然只是说明您可以为缺失的 2 列发明数据。

点2:

所以现在你需要阅读MySQL Manual - String functions section(我不是为你编码)

在这里,您将看到您可以使用 table1 中任何列的值并从中挑选位并将位连接在一起,而不仅仅是对缺失列的硬编码数据。

寻找 SUBSTRING 和 INSTR 等等。这将允许您从现有列构建缺少的字段。

单独测试 sub select 子句,直到它产生所需的输出。

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多