是否可以在MYSQL中动态选择一个列名,该列名是N个已知值中的1个? [英] Is it possible to dynamically select a column name in MYSQL where the column name is 1 of N known values?

查看:90
本文介绍了是否可以在MYSQL中动态选择一个列名,该列名是N个已知值中的1个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心答案将是直接的否",但我想知道是否可以在MySQL中执行以下操作:

I fear the answer will be a straight 'no', but I was wondering if it's possible to do something such as the following in MySQL:

SELECT (title||label||name) FROM table

即,从table中选择一个列,可以称为titlelabelname.

i.e Select a single column, which may be called title, label or name, from table.

原因是:查询将在已知table的地方动态生成,但是(由于我无法控制的原因)在其他表中没有一致的命名约定.

Reason being: the query will be dynamically generated where table is known but (due to reasons beyond my control) there is no consistent naming convention in the other tables.

推荐答案

可以解决问题.

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='YOUR_TABLE_NAME' AND COLUMN_NAME IN ('name', 'label', 'title') into @colname;
SET @table = 'YOUR_TABLE_NAME';
SET @query = CONCAT('SELECT ',@colname,' FROM ', @table);

PREPARE stmt FROM @query;
EXECUTE stmt;

此处的启示:将字符串动态转换为列名. MySQL

这篇关于是否可以在MYSQL中动态选择一个列名,该列名是N个已知值中的1个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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