mysql: referring to columns by numbers

2019-03-03 07:41发布

问题:

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;


标签: mysql aliases