Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 557
user2999461 Avatar asked Nov 16 '13 14:11

user2999461


People also ask

Can you use a variable for a column name in SQL?

How do I give a column a variable name in SQL Server? SELECT Datecolumn as @ColumnName.

How do you reference a variable in MySQL?

User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ . A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var' , @"my-var" , or @`my-var` ). User-defined variables are session specific.

Can I use MySQL keyword as column name?

Using Keywords in Tables or Columns Generally, SQL developers advise against using reserved words. However, if you want (or need) to use a reserved word as a table or column name, you can place the respective identifier in special quotation marks, so-called backticks (` `), in the SQL statements.

HOW CAN GET row values as column names in MySQL?

Display Row Values as Columns in MySQL Dynamically You can customize the above query as per your requirements by adding WHERE clause or JOINS. If you want to transpose only select row values as columns, you can add WHERE clause in your 1st select GROUP_CONCAT statement.


1 Answers

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;
like image 173
fthiella Avatar answered Oct 02 '22 21:10

fthiella