【问题标题】:mysql get table column names in alphabetical ordermysql 按字母顺序获取表列名
【发布时间】:2011-04-17 00:12:15
【问题描述】:

是否可以查询 MySQL 数据库以按字母顺序获取表的列名?我知道

SHOW COLUMNS `table_name`;

DESCRIBE `table_name`;

会给我一个表中的列列表(以及其他信息),但是是否可以更改查询以使列按字母顺序排序。添加 ORDER BY 'Field' 不起作用,它给出了语法错误。

【问题讨论】:

    标签: sql mysql sql-order-by


    【解决方案1】:

    ANSI INFORMATION_SCHEMA tables (in this case, INFORMATION_SCHEMA.COLUMNS) 在 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
    

    【讨论】:

    • 效果很好,会再次使用。你能告诉我为什么 c.table_schema 条件存在,因为它似乎没有它就可以工作。
    • @John Scipione:双破折号“--”是 SQL 中的注释; table_schema 从查询中被注释掉。删除双破折号以便在语句中对其进行评估。
    • 像魅力一样工作!我还使用了按列名分组。
    【解决方案2】:

    在我使用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】:

      如果您想了解更多详细信息,下面的查询非常方便:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        相关资源
        最近更新 更多