Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql field name from variable

Tags:

is it possible to select field which name is string?

SELECT 'fieldname' FROM table

i need this for trigger to have dynamic field names something like

SET fieldname = NEW.`name`; UPDATE table SET fieldname = 1 ;  
like image 563
samrockon Avatar asked Dec 13 '10 12:12

samrockon


People also ask

How do I find a specific field in MySQL?

How to list all tables that contain a specific column name in MySQL? You want to look for tables using the name of columns in them. SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA. COLUMNS WHERE COLUMN_NAME IN('column1', 'column2') AND TABLE_SCHEMA = 'schema_name';

How can I get column names from a table in MySQL?

You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.

Can I use MySQL keyword as column name?

In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL.


2 Answers

If the string is in your external application (like PHP), sure, just construct the MySQL statement.

If the string is inside a MySQL table, you can't. MySQL has no eval() or such function. The following is impossible:

Suppose you have a table queries with a field columnname that refers to one of the column names in the table mytable. There might be additional columns in queries that allow you to select the columnname you want.

INSERT INTO queries  (columname) VALUES ("name") SELECT (select columnname from queries) from mytable 

You can however work with PREPARED STATEMENTS. Be aware this is very hacky.

SELECT columnname from queries into @colname; SET @table = 'mytable'; SET @s = CONCAT('SELECT ',@colname,' FROM ', @table);  PREPARE stmt FROM @s; EXECUTE stmt; 
like image 74
Konerak Avatar answered Oct 27 '22 23:10

Konerak


If you want to select more than one column:

SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.`COLUMNS` C  WHERE table_name = 'MyTb' AND COLUMN_NAME LIKE '%whatever%' INTO @COLUMNS;  SET @table = 'MyTb'; SET @s = CONCAT('SELECT ',@columns,' FROM ', @table);  PREPARE stmt FROM @s; EXECUTE stmt; 
like image 22
Ilu Avatar answered Oct 28 '22 01:10

Ilu