Home >Database >Mysql Tutorial >How Can I Dynamically Select Columns in MySQL Queries?
In scenarios where the table structure is unknown or subject to change, selecting specific columns becomes challenging. This tutorial demonstrates a method to dynamically retrieve column names and construct a query to select desired columns.
To dynamically fetch column names, we can combine the following queries:
One potential approach involves joining these queries and using the GROUP_CONCAT() function to concatenate the desired column names:
SELECT CONCAT('SELECT ', GROUP_CONCAT(c.COLUMN_NAME), ' FROM table_name;') INTO @query FROM information_schema.columns c WHERE c.TABLE_NAME = 'table_name' AND c.COLUMN_NAME LIKE 'prefix%';
This query generates a string containing a SELECT statement that includes specific columns matching the specified criteria.
Once the query string is constructed, we can prepare and execute it:
PREPARE stmt FROM @query; EXECUTE stmt;
The above is the detailed content of How Can I Dynamically Select Columns in MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!