变量的mysql字段名

时间:2010-12-13 12:23:45

标签: mysql

是否可以选择名称为字符串的字段?

SELECT 'fieldname' FROM table

我需要这个触发器才能拥有动态字段名称

之类的东西
SET fieldname = NEW.`name`;
UPDATE table SET fieldname = 1 ; 

3 个答案:

答案 0 :(得分:21)

如果字符串在您的外部应用程序(如PHP)中,请确保只构造MySQL语句。

如果字符串在MySQL表中,则不能。 MySQL没有eval()或这样的功能。以下是不可能的:

假设您有一个表queries,其字段columnname引用表mytable中的一个列名称。 queries中可能还有其他列允许您选择所需的columnname

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

但您可以使用PREPARED STATEMENTS。请注意,这非常黑客。

SELECT columnname from queries into @colname;
SET @table = 'mytable';
SET @s = CONCAT('SELECT ',@colname,' FROM ', @table);

PREPARE stmt FROM @s;
EXECUTE stmt;

答案 1 :(得分:2)

就像这些正确答案一样,您也可以在一个存储过程中完成它,这对我在MySQL 8x社区中非常适用:

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `SP_LIST_COLLECTORS`(
    IN P_email VARCHAR(60),#Admin email
    IN P_password_hash VARCHAR(255),#Admin hash
    IN P_filter_field VARCHAR(80),
    IN P_filter_value VARCHAR(255)
)
BEGIN
DECLARE V_filter_field VARCHAR(80);
    SET V_filter_field = P_filter_field;
    BEGIN
        GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
        SELECT 'ERROR' AS STATUS, CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS MESSAGE;
    END;
    SET @statement = CONCAT('SELECT collector_id, email, address, post_code, phone, alt_phone, contact_name
    FROM collectors_table
    WHERE ',P_filter_field, '=\'', P_filter_value, '\';');
    #SELECT collector_id, email, address, post_code, phone, alt_phone, contact_name FROM collectors_table WHERE (V_filter_field) = P_filter_value;
    PREPARE stmnt FROM @statement;
    EXECUTE stmnt;
END

答案 2 :(得分:0)

如果要选择多个列:

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;