MySQL-如何使用变量作为列名 [英] MySQL - How to use a variable as column name

查看:86
本文介绍了MySQL-如何使用变量作为列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用注册表作为列名,但是注册表是可变的,我不知道它何时更改.

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

示例:

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

一个想要做的事情:

医学(使用Config的内容作为列名称)='补救名称'(作为注册表)

Medicine (use content of Config as column name) = 'Remedy Name' (as registry)

我尝试了什么?

SET @CONFIG = SELECT CONFIG;

SELECT FIELDCONTENT AS @CONFIG FROM TABLENAME;

MySql说我不能使用变量作为列名.还有其他方法吗?

MySql says that I can't use a variable as column name. There's other way?

实际配置内容医学RemedyName

actual Config Content Medicine RemedyName

想要的药物
RemedyName

Wanted Medicine
RemedyName

谢谢!

推荐答案

我的想法是使用准备好的语句:

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;

这篇关于MySQL-如何使用变量作为列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆