MySQL - How to use a variable as column name

故事扮演 提交于 2021-02-18 07:04:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!