MySQL - how to use a variable as a column name

I want to use the registry as the column name, but the registry is variable, and I don't know when it will change.

Example:

Config (field) = 'Medicine'
FieldContent (another field) = 'Remedy name'

You want to do this:

Medicine (use the contents of Config as a column name) = 'Remedy Name' (as a registry)

What have i tried?

SET @CONFIG = SELECT CONFIG;

SELECT FIELDCONTENT AS @CONFIG FROM TABLENAME;

MySql says that I cannot use the variable as the column name. Is there another way?

current RemedyName Medicine configuration contents

Requires
  RemedyName medicine

Thanks!

+4
source share
1 answer

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;
+8
source

All Articles