SELECT in mysql using column number instead of name

折月煮酒 提交于 2019-12-06 05:30:50

问题


Is there any way to do something like :

SELECT * FROM TABLE WHERE COLUMN_NUMBER = 1;

?


回答1:


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.

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.

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. And, in that case, its a name given to the column in the inline view that has to be referenced in the outer query.




回答2:


No, you can't. Column order doesn't really matter in MySQL. See the below question for more details.

mysql - selecting values from a table given column number




回答3:


How I did it:

I'm trying to take (last 3 values of) column number 4 in sometable.

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.




回答4:


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";


来源:https://stackoverflow.com/questions/17626503/select-in-mysql-using-column-number-instead-of-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!