简体   繁体   English

如何使用变量作为 SELECT 语句的列名

[英]How to use a variable as a column name for a SELECT statement

I am unable to use a previously defined variable representing a column name in a SELECT statement and need some help.我无法在 SELECT 语句中使用先前定义的表示列名的变量,需要一些帮助。

TABLE:桌子:

main | i1 | i2 ||..........| i24  | i25 |
.
. 
17 | 121 | 123| .........
19 | 123 | 212| .........   | 4832 | 56392 |

From a previous SELECT/SET statement @indent variable equaled 25. As I can't use an integer as a column name the columns are i1 - i25 in the tableindex.从之前的 SELECT/SET 语句中,@indent 变量等于 25。由于我不能使用整数作为列名,因此 tableindex 中的列是 i1 - i25。 However when I attempt to use the @VARIABLE in the SELECT statment I get the following:但是,当我尝试在 SELECT 语句中使用 @VARIABLE 时,我得到以下信息:

SET @colindex1=(CONCAT(i, @indent);    
SELECT @colindex1 FROM tableindex WHERE main=19;

RESULTS结果

| @colindex1 |
|  i25  |

SHOULD BE THE VALUE OF THE CELL:应该是单元格的值:

| i25  |
| 56392|

So the next attach was to use a DECLARE statement.所以下一个附件是使用 DECLARE 语句。

DECLARE @colindex1 VARCHAR;

But I got the following error:但我收到以下错误:

ERROR 1064 (42000): You have an error in your SQL syntax; ERROR 1064 (42000):您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'declare @colindex1 INT' at line 1检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“declare @colindex1 INT”附近使用正确的语法

I need to combine my integer (25) value with the letter (i) for the column "i25' and then use it a SELECT statement. However I am failing at this point.我需要将我的整数 (25) 值与列“i25”的字母 (i) 结合起来,然后使用 SELECT 语句。但是我在这一点上失败了。

Can someone help有人可以帮忙吗

BASED ON ANSWER HERE IS A TEST USING THE SPECIFIED SYNTAX AND ERROR:根据答案,这里是使用指定语法和错误的测试:

SET @indent = 1+24; 
SET @colindent1 = (SELECT CONCAT('i', @indent)); 
set @stmt = (SELECT @colindent1 FROM tableindex WHERE main=19);
 PREPARE thestmt FROM @stmt; 

ERROR 1064 (42000): ..near 'i25' at line 1 AAAAHH! ERROR 1064 (42000): ..near 'i25' at line 1 AAAAHH! WHAT AM I DOING WRONG?我究竟做错了什么?

HOWEVER:然而:

set @stmt = (SELECT i25 FROM tableindex WHERE main=19);
Query OK, 0 rows affected (0.00 sec)

To use variables to represent columns (or tables), you need to use PREPARE/EXECUTE.要使用变量来表示列(或表),您需要使用 PREPARE/EXECUTE。 Try something like this:尝试这样的事情:

    SET @colindex1=(CONCAT(i, @indent);    
    SET @stmt = 'SELECT @colindex1 FROM tableindex WHERE main=19';
    PREPARE thestmt FROM @stmt;
    EXECUTE thestmt;

Keep it simple:把事情简单化:

SET @stmt = CONCAT('SELECT i', @indent,' FROM tableindex WHERE main=19';
PREPARE thestmt FROM @stmt;
EXECUTE thestmt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM