在MySQL中使用SELECT查询作为列名

时间:2013-07-21 21:53:13

标签: mysql auto-increment information-schema


我想在我的表中获取auto_increment列的值(示例)。但是,我没有auto_increment字段的名称。我目前正在使用以下查询来确定该字段的名称:

SELECT column_name FROM information_schema.columns WHERE table_name = 'example' AND extra = 'auto_increment' LIMIT 1;

我现在想将此查询的结果作为“字符串”传递给我的实际查询,并获取值。如果我想一气呵成,我该怎么做,因为下面的查询应该给我所有使用的auto_increment值,只产生上面的结果 - 即auto_increment列名。

SELECT (
   SELECT column_name
   FROM information_schema.columns
   WHERE table_name =  'example'
   AND extra =  'auto_increment'
   LIMIT 1
) AS pri
FROM example 

任何想法都会被赞赏:)
很多问候,

安德烈亚斯

1 个答案:

答案 0 :(得分:0)

以下是使用prepareexecute执行此操作的示例:

SELECT @s := concat('select `', column_name, '` from example e')
FROM information_schema.columns
WHERE table_name =  'example' AND extra =  'auto_increment'
LIMIT 1

prepare stmt from @s;
execute stmt;
deallocate prepare stmt;
相关问题