gpt4 book ai didi

mysql - 是否可以在 INSERT 的子查询中选择列名?

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:07 28 4
gpt4 key购买 nike

是否可以在 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 |
+------+---------+---------+---------+

最佳答案

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

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'

关于mysql - 是否可以在 INSERT 的子查询中选择列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14042804/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com