MySql: Show columns but exclude everything except the field names

前端 未结 6 618
陌清茗
陌清茗 2021-01-30 13:36

I\'d like to pull a table\'s field names from MySql into python, and I know that

\'show columns from project\'

will work. And I\'ve read that

相关标签:
6条回答
  • 2021-01-30 13:45

    You can query MySQL's information_schema database directly for the fieldnames:

    select distinct(COLUMN_NAME) from information_schema.COLUMNS where TABLE_NAME='posts';
    
    0 讨论(0)
  • 2021-01-30 13:48
    SHOW COLUMNS FROM `table_name`
    

    This MySQL query will work best, it will show all fields of a MySQL table.

    0 讨论(0)
  • 2021-01-30 13:51

    If your goal is a comma-delimited list (Not very Python literate, but that's mostly what you'd want in PHP and Perl) GROUP_CONCAT is your friend:

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

    If you need them quoted this gives you all EXCEPT the outermost quotes:

    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
    
    0 讨论(0)
  • 2021-01-30 14:00
    SELECT column_name
    FROM information_schema.columns
    WHERE  table_name = 'your_table'
       AND table_schema = 'database_name'
    
    0 讨论(0)
  • 2021-01-30 14:00

    Pipe the answer to awk:

    SHOW columns FROM project; | awk '{ print $1 }'
    
    0 讨论(0)
  • 2021-01-30 14:08

    Although it looks more elegant, you don't need awk for this. MySQL's information_schema.columns table has the info you need.

    -- DESCRIBE THE HECK OUT OF THE ENTIRE 'table_name' table in the 'database_name' database

    SHOW COLUMNS
    FROM database_name.table_name ;
    

    -- SHOW JUST THE COLUMN NAMES for 'table_name' table in the 'database_name' database.

    SELECT column_name
    FROM information_schema.columns
    WHERE table_schema = 'database_name'
    AND table_name = 'table_name' ;
    
    0 讨论(0)
提交回复
热议问题