Dynamic Column Name Selection in MySQL
When working with MySQL tables whose structures may change frequently, it can be challenging to select specific column names hardcoded in your SQL statements. To overcome this, a technique can be employed that dynamically selects column names based on the table's current schema.
In response to the presented question, a SQLFiddle example is provided:
CREATE TABLE atable ( prefix1 VARCHAR(10) ,prefix2 VARCHAR(10) ,notprefix3 INT ,notprefix4 INT ); INSERT INTO atable VALUES ('qwer qwer', 'qwerqwer', 1, 1); INSERT INTO atable VALUES ('qwer qwer', 'asdfaasd', 1, 1); INSERT INTO atable VALUES ('qwer qwer', 'qrt vbb', 1, 1); INSERT INTO atable VALUES ('qwer qwer', 'sdfg sdg', 1, 1); SELECT CONCAT('SELECT ', GROUP_CONCAT(c.COLUMN_NAME), ' FROM atable;') INTO @query FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_NAME = 'atable' AND c.COLUMN_NAME LIKE 'prefix%' ORDER BY c.ORDINAL_POSITION; PREPARE stmt FROM @query; EXECUTE stmt;
This example is useful for selecting column names that share a common prefix, such as "prefix1" and "prefix2". However, it has a few limitations:
The above is the detailed content of How Can I Dynamically Select Column Names in MySQL Based on Schema Changes?. For more information, please follow other related articles on the PHP Chinese website!