MySQL: How to select a column by number?

冷暖自知 提交于 2020-01-14 05:33:20

问题


I'm writing a program, and I have the need to SELECT column names by number, rather than by name.

That is, say the attributes to my table are:

SSN, FirstName, LastName, MiddleName, Address, City, State, Zip

How could I select the data just from columns 0 (SSN), 1 (FirstName), 2(LastName), 6 (State)

Is there a way to do this without delving into information schema?


回答1:


You should reconsider your design. A table can be changed, it can evolve, column order is very fickle. You should NOT hardcode column numbers.


ADDENDUM

By "evolve" and "fickle", I don't mean that the database engine can move them around. That's pretty much fix. No, I mean that needs can change in the future and the table design can be updated. It will be easier in the future to adapt your old code if you list the actual column names rather than the column position order. Think of column position just like row position: don't expect a particular order in the result based on input order, but rather make your query give you the order you need.




回答2:


Ok, so don't do this, but, if you really need to do this you can use COLUMNS.ORDINAL_POSITION in the information schema.




回答3:


SELECT `0`,`1`,`2`,`6` FROM `table` ORDER BY `ssn`


来源:https://stackoverflow.com/questions/7494372/mysql-how-to-select-a-column-by-number

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