问题
I want to use a registry as a column name but the registry is variable and I don't know when it changes.
Example:
Config (field) = 'Medicine'
FieldContent (another field) = 'Remedy name'
A want to make this:
Medicine (use content of Config as column name) = 'Remedy Name' (as registry)
What have I tried?
SET @CONFIG = SELECT CONFIG;
SELECT FIELDCONTENT AS @CONFIG FROM TABLENAME;
MySql says that I can't use a variable as column name. There's other way?
actual Config Content Medicine RemedyName
Wanted Medicine
RemedyName
Thanks!
回答1:
My idea is to use a prepared statement:
SET @config := (SELECT CONFIG FROM yourtable WHERE id=1);
SET @sql := CONCAT('SELECT FIELDCONTENT AS `', @config, '` FROM TABLENAME');
PREPARE stmt FROM @sql;
EXECUTE stmt;
来源:https://stackoverflow.com/questions/20019484/mysql-how-to-use-a-variable-as-column-name