mysql: referring to columns by numbers

被刻印的时光 ゝ 提交于 2020-01-11 14:15:09

问题


I want to give columns aliases without knowing their names, but only their number in the table.

Something like this:

select firstColumn as myId, secondColumn as myName, thirdColumn as myLastName

where I don't know the actual names of the columns

(I understand that the need sounds strange. And yes I can know the names of the columns. This is a technical question, please answer if you know the technical answer, regardless of the motivation. Thank you!)


回答1:


The closest you could do is use INFORMATION_SCHEMA.COLUMNS to find the column name from the ordinal position. I realize this isn't what you asked for, but I think it may be as close as you can get. For instance, you could build a select statement having the 1st, 2nd and 5th columns as follows:

SELECT CONCAT("SELECT ",
   GROUP_CONCAT(column_name SEPARATOR ", "),
   " FROM ", table_name)
FROM information_schema.columns
WHERE table_schema = database() 
    AND table_name = 'my_table' 
    AND ordinal_position IN (1,2,5) 
GROUP BY table_name 
ORDER BY ordinal_position;


来源:https://stackoverflow.com/questions/7111980/mysql-referring-to-columns-by-numbers

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