【问题标题】:Is it possible to select a column name in a subquery for INSERT?是否可以在子查询中为 INSERT 选择列名?
【发布时间】:2012-12-26 15:45:34
【问题描述】:

是否可以在子查询中为 INSERT 选择列名?

例如,如果我有一个表 (table1),它将事件映射到另一个表 (table2) 中的列:

表1:

+------+--------+---------+
| id   | events | columns |
+------+--------+---------+
|    1 | event1 | column1 |
|    2 | event2 | column2 |
|    3 | event3 | column3 |
|    4 | event4 | column1 |
|    5 | event5 | column2 |
|    6 | event6 | column3 |
+------+--------+---------+

表2:

+------+---------+---------+---------+
| id   | column1 | column2 | column3 |
+------+---------+---------+---------+
|  ... |     ... |     ... |     ... |
+------+---------+---------+---------+

是否有SQL语句,如:

INSERT INTO table2 
(
    id, 
    (SELECT columns          /* the interesting subquery */
     FROM table1 
     WHERE events='event1')
) 
VALUES (1, 123);

这将导致插入带有值的 table2:

+------+---------+---------+---------+
| id   | column1 | column2 | column3 |
+------+---------+---------+---------+
|    1 |     123 |    NULL |    NULL |
+------+---------+---------+---------+

【问题讨论】:

  • 不,你需要动态 sql 来做到这一点,我认为 MySql 仅以 Prepared Statements 的形式对此提供有限的支持
  • table1 中的columns 列可以有无限的列数,还是只有3 个?
  • 在 Table1 中再添加一个字段作为值,用于存储您尝试存储在 table2 中的值。
  • tsabz - 仅限列数。将我的问题视为分组问题。

标签: mysql sql insert subquery


【解决方案1】:

不,您不能对标识符使用表达式。你可以这样做:

insert into table2 (id, column1, column2, column3)
select 1,
  case columns when 'column1' then 123 else null end,
  case columns when 'column2' then 123 else null end,
  case columns when 'column3' then 123 else null end
from table1
where events = 'event1'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多