MySQL 来自变量的mysql字段名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4428761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql field name from variable
提问by samrockon
is it possible to select field which name is string?
是否可以选择名称为字符串的字段?
SELECT 'fieldname' FROM table
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 ;
回答by Konerak
If the string is in your external application (like PHP), sure, just construct the MySQL statement.
如果字符串在您的外部应用程序(如 PHP)中,当然,只需构建 MySQL 语句。
If the string is inside a MySQL table, you can't. MySQL has no eval()
or such function. The following is impossible:
如果字符串在 MySQL 表中,则不能。MySQL 没有eval()
或没有这样的功能。以下情况是不可能的:
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.
假设您有一个表queries
,其字段columnname
引用表中的列名之一mytable
。可能还有其他列queries
允许您选择所需的列columnname
。
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.
但是,您可以使用PREPARED STATEMENTS。请注意,这是非常hacky。
SELECT columnname from queries into @colname;
SET @table = 'mytable';
SET @s = CONCAT('SELECT ',@colname,' FROM ', @table);
PREPARE stmt FROM @s;
EXECUTE stmt;
回答by Ilu
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;