[英]How I can use the result of SELECT statement in ALTER TABLE in MySQL?
I have a table with some properties.我有一个包含一些属性的表。 I would like use these properties to create some columns in another table (ALTER TABLE).
我想使用这些属性在另一个表 (ALTER TABLE) 中创建一些列。
The follow SELECT statement result in multiple results:以下 SELECT 语句导致多个结果:
SELECT property FROM table1 GROUP BY property;
Result example:结果示例:
For each result of select statement above, perform:对于上面select语句的每一个结果,执行:
ALTER TABLE table2 ADD property boolean null;
How do?怎么办?
Here is an example for postgres.这是 postgres 的示例。 With little modification you can use it for mysql too.
稍作修改,您也可以将其用于 mysql。
DO $$
DECLARE row_results record;
BEGIN FOR row_results IN
SELECT column_name
FROM information_schema.columns
WHERE table_schema='public'
AND table_type='BASE TABLE'
AND table_name = 'table1'
LOOP
EXECUTE format('ALTER TABLE table2 ADD COLUMN %I boolean NULL', row_results.column_name);
END LOOP;
END$$;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.