【问题标题】:MySql: Show columns but exclude everything except the field namesMySql:显示列但排除除字段名之外的所有内容
【发布时间】:2011-04-02 21:21:55
【问题描述】:

我想把一个表的字段名从 MySql 拉到 python 中,我知道

'show columns from project'

会起作用。而且我读到您可以添加“WHERE ...”以将其限制在某些字段中。但我找不到如何只返回列名的示例,而不是类型、键、空、额外信息。

提取列的所有字段名称而不提取其他描述内容的匹配标准是什么?

【问题讨论】:

  • 相关,如果感兴趣,我在this Answer写了一个Describe All Tables

标签: mysql


【解决方案1】:
SELECT column_name
FROM information_schema.columns
WHERE  table_name = 'your_table'
   AND table_schema = 'database_name'

【讨论】:

  • 太棒了!我在两台服务器上测试了 phpMyAdmin。但是每台服务器上只有一个 information_schema 数据库,并且保存服务器上的不同数据库中可能存在多个具有相同表名的表。在这种情况下,它如何知道要提取哪个表列列表?
  • 查看table_schema 专栏
  • 对我来说,它也可以在没有“AND table_schema = 'database_name'”的情况下工作
【解决方案2】:

虽然它看起来更优雅,但您不需要 awk。 MySQL 的 information_schema.columns 表有你需要的信息。

-- 描述 'database_name' 数据库中整个 'table_name' 表的情况

SHOW COLUMNS
FROM database_name.table_name ;

-- 仅显示“database_name”数据库中“table_name”表的列名。

SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'database_name'
AND table_name = 'table_name' ;

【讨论】:

    【解决方案3】:

    如果你的目标是一个逗号分隔的列表(不是很懂 Python,但这主要是你在 PHP 和 Perl 中想要的)GROUP_CONCAT 是你的朋友:

    SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your-table-name-here' GROUP BY TABLE_NAME ORDER BY ORDINAL_POSITION
    

    如果您需要引用它们,这将为您提供除最外层引号之外的所有内容:

    SELECT GROUP_CONCAT(column_name SEPARATOR '","') FROM information_schema.columns WHERE table_name='your-table-name-here' GROUP BY TABLE_NAME ORDER BY ORDINAL_POSITION
    

    【讨论】:

      【解决方案4】:

      您可以直接在 MySQL 的 information_schema 数据库中查询字段名:

      select distinct(COLUMN_NAME) from information_schema.COLUMNS where TABLE_NAME='posts';
      

      【讨论】:

        【解决方案5】:
        SHOW COLUMNS FROM `table_name`
        

        这个 MySQL 查询效果最好,它将显示 MySQL 表的所有字段。

        【讨论】:

          【解决方案6】:

          将答案传递给 awk:

          SHOW columns FROM project; | awk '{ print $1 }'
          

          【讨论】:

            猜你喜欢
            • 2018-12-18
            • 1970-01-01
            • 1970-01-01
            • 2017-04-03
            • 2021-06-28
            • 1970-01-01
            • 2012-12-03
            • 2022-08-17
            • 1970-01-01
            相关资源
            最近更新 更多