mysql field name from variable

前端 未结 3 900
别那么骄傲
别那么骄傲 2020-11-28 13:17

is it possible to select field which name is string?

SELECT \'fieldname\' FROM table

i need this for trigger to have dynamic field names somethi

3条回答
  •  天涯浪人
    2020-11-28 14:02

    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;
    

提交回复
热议问题