简体   繁体   English

使用列号而不是名称在mysql中进行SELECT

[英]SELECT in mysql using column number instead of name

Is there any way to do something like : 有什么方法可以做以下事情:

SELECT * FROM TABLE WHERE COLUMN_NUMBER = 1;

?

No, you can't. 不,你不能。 Column order doesn't really matter in MySQL. 列顺序在MySQL中并不重要。 See the below question for more details. 有关详细信息,请参阅以下问题。

mysql - selecting values from a table given column number mysql - 从给定列号的表中选择值

If your table has a column named COLUMN_NUMBER and you want to retrieve rows from the table where that column contains a value of '1', that query should do the trick. 如果您的表有一个名为COLUMN_NUMBER的列,并且您想要从该表中包含值为“1”的表中检索行,那么该查询应该可以解决问题。

I suspect that what you are trying to do is reference an expression in the select list with an alias. 我怀疑你要做的是用别名引用选择列表中的表达式。 And that is not supported. 这不受支持。 An expression in the WHERE clause that references a column must reference the column by name. WHERE子句中引用列的表达式必须按名称引用列。

We can play some tricks with inline views, to give an alias to an expression, but this is not efficient in terms of WHERE predicates, because of the way MySQL materializes a derived table. 我们可以使用内联视图来播放一些技巧,为表达式提供别名,但就WHERE谓词而言,这是没有效率的,因为MySQL实现派生表的方式。 And, in that case, its a name given to the column in the inline view that has to be referenced in the outer query. 并且,在这种情况下,它是内联视图中的列的名称,必须在外部查询中引用。

How I did it: 我是怎么做到的

I'm trying to take (last 3 values of) column number 4 in sometable . 我试图在sometablecolumn number 4 column number (最后3个值)。

set @mydb=(SELECT DATABASE());
set @mycol=(select COLUMN_NAME from information_schema.columns where
         table_schema=@mydb and table_name='sometable' and ordinal_position = 4);
SELECT Date,@mycol FROM sometable ORDER BY Date DESC LIMIT 3;

Of course, if Database name is known, first line could by whiped and @mydb replaced by real database name. 当然,如果数据库名称已知,则第一行可以通过whiped而@mydb替换为真实数据库名称。

You can do this trick 你可以做到这一点

Example: 例:

$query="select * from employee";

$result=mysql_query($query);

$meta=mysql_fetch_field($result,0)  // 0 is first field in table  , 1 is second one ,,, etc

$theNameofFirstField=$meta->name;    // this well return first  field name in table


// now you can use it in other query

$seconQuery="select $theNameofFirstField from employee";

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

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