user2999461
user2999461

Reputation: 51

MySQL - How to use a variable as column name

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!

Upvotes: 5

Views: 8353

Answers (1)

fthiella
fthiella

Reputation: 49049

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;

Upvotes: 9

Related Questions