选择除一个之外的所有列

时间:2013-04-02 11:32:47

标签: mysql stored-procedures prepared-statement

我需要从表“ticket”中选择所有列,除了一列“depname” 以下准备好的声明无法按预期工作。

PREPARE stmt1 FROM 'SELECT ? from magon.ticket limit 2';

select GROUP_CONCAT(COLUMN_NAME) into @clm from COLUMNS  where TABLE_SCHEMA = 'magon' and TABLE_NAME = 'ticket' and COLUMN_NAME NOT IN ('depname')  GROUP BY TABLE_SCHEMA, TABLE_NAME;

execute stmt1 using @clm;

它返回列列表两次(由于限制2),但不返回实际数据。

1 个答案:

答案 0 :(得分:5)

不幸的是,您无法参数化列名和表名,因为它们是标识符。但是你可以连接字符串中的值,

SET @colName = (SELECT  GROUP_CONCAT(COLUMN_NAME) 
                FROM    COLUMNS  
                WHERE   TABLE_SCHEMA = 'magon' AND 
                        TABLE_NAME = 'ticket' AND 
                        COLUMN_NAME NOT IN ('depname')  
                GROUP   BY TABLE_SCHEMA, TABLE_NAME);
PREPARE stmt1 FROM CONCAT('SELECT ', @colName ,' FROM magon.ticket LIMIT 2');
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;