简体   繁体   中英

Alter table using sub select

I have two tables. one which is a field info table and the other is a field data table.

by default all field data table columns are set to text fields of some sort (varchar, text, etc)

what i would like to do is this. Instead of creating the manual ALTER TABLE query:

ALTER TABLE `field_data` 
CHANGE COLUMN `field_id_2` `field_id_2` decimal NOT NULL, 
CHANGE COLUMN `field_id_3` `field_id_3` decimal NOT NULL,
CHANGE COLUMN `field_id_22` `field_id_22` decimal NOT NULL,
CHANGE COLUMN `field_id_23` `field_id_23` decimal NOT NULL,
CHANGE COLUMN `field_id_25` `field_id_25` decimal NOT NULL,
CHANGE COLUMN `field_id_27` `field_id_27` decimal NOT NULL,
CHANGE COLUMN `field_id_30` `field_id_30` decimal NOT NULL,
CHANGE COLUMN `field_id_66` `field_id_66` decimal NOT NULL,
CHANGE COLUMN `field_id_72` `field_id_72` decimal NOT NULL;

I would like to write a dynamic ALTER TABLE query based on the field_info table, right now I get those field IDs by doing this query:

SELECT field_id FROM `field_info` WHERE `field_type` = 'a_decimal_field'

which returns the values: 2, 3, 22, 23, etc.

So I would need a query (if possible) that alters the table based on the sub select concatenating field_id_ to the result of each sub select and changes the type of that column to decimal.

I know I can do this in php by constructing the query, but I am specifically looking for a pure mysql solution if possible.

SELECT CONCAT('ALTER TABLE `field_data` ', 
  GROUP_CONCAT(' CHANGE COLUMN `field_id_', field_id, '` ',
    ' `field_id_', field_id, '` DECIMAL NOT NULL')) 
FROM `field_info` 
WHERE `field_type` = 'a_decimal_field'
INTO @sql;

PREPARE stmt FROM @sql;

EXECUTE stmt;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM