mysql get table column names in alphabetical order

白昼怎懂夜的黑 提交于 2019-11-27 01:48:31

问题


Is it possible to query a MySQL database to get the column names of a table in alphabetical order? I know that

SHOW COLUMNS `table_name`;

or

DESCRIBE `table_name`;

will give me a list of the columns in a table (along with other info), but is it possible to alter the query in order to get the columns sorted alphabetically. Adding ORDER BY 'Field' didn't work, it gave a syntax error.


回答1:


The ANSI INFORMATION_SCHEMA tables (in this case, INFORMATION_SCHEMA.COLUMNS) provide more flexibility in MySQL:

SELECT c.column_name
  FROM INFORMATION_SCHEMA.COLUMNS c
 WHERE c.table_name = 'tbl_name'
-- AND c.table_schema = 'db_name'    
ORDER BY c.column_name



回答2:


Every field was listed twice until I used group by column name

 select c.COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS c 
 where c.TABLE_NAME = `'tbl_name'` 
 group by c.column_name 
 order by c.column_name



回答3:


If you want more details, below query is really handy:

   SELECT COLUMN_NAME  as 'Field',
   COLUMN_TYPE    as 'Type',
   IS_NULLABLE    as 'Null',
   COLUMN_KEY     as 'Key',
   COLUMN_DEFAULT as 'Default',
   EXTRA          as 'Extra'
   from INFORMATION_SCHEMA.COLUMNS
   where TABLE_NAME   = 'my table' and
   TABLE_SCHEMA = 'my database'
   add ordering
   order by Type;  -- 


来源:https://stackoverflow.com/questions/3791123/mysql-get-table-column-names-in-alphabetical-order

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