如何获取MySQL中所有表的所有列的名称?

问题描述 投票:163回答:10

有没有一种快速的方法来获取MySQL中所有表的所有列名,而不必列出所有表?

mysql database-schema database-metadata
10个回答
267
投票
select * from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

2
投票

问题是:

有没有一种快速的方法可以从MySQL的所有表中获取所有COLUMN NAMES,而无需列出所有表格?

SQL获取每列的所有信息

select * from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

SQL获取所有COLUMN NAMES

select COLUMN_NAME from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

44
投票

要列出MySQL中表的所有字段:

select * 
  from information_schema.columns 
 where table_schema = 'your_DB_name' 
   and table_name = 'Your_tablename'

25
投票
SELECT * FROM information_schema.columns
WHERE table_schema = DATABASE()
ORDER BY table_name, ordinal_position

由于我没有足够的评论来评论,所以这是一个小改进(在我看来)超过了nick rulez的优秀答案:用WHERE table_schema = 'your_db'取代WHERE table_schema = DATABASE()


24
投票

最好使用以下查询来轻松获取所有列名

Show columns from tablename


17
投票

如果它对其他人有用,那么这将为您提供以逗号分隔的每个表中列的列表:

SELECT table_name,GROUP_CONCAT(column_name ORDER BY ordinal_position)
FROM information_schema.columns
WHERE table_schema = DATABASE()
GROUP BY table_name
ORDER BY table_name

注意:使用具有大量列和/或长字段名称的表时,请注意group_concat_max_len限制,这可能导致数据被截断。


6
投票
<?php
        $table = 'orders';
        $query = "SHOW COLUMNS FROM $table";
        if($output = mysql_query($query)):
            $columns = array();
            while($result = mysql_fetch_assoc($output)):
                $columns[] = $result['Field'];
            endwhile;
        endif;
        echo '<pre>';
        print_r($columns);
        echo '</pre>';
?>

4
投票

answer posted by @suganya类似,这不能直接回答问题,但是对于单个表来说是更快的替代方案:

DESCRIBE column_name;

3
投票

我很久以前写过这个愚蠢的东西,但实际上还是偶尔使用它:

https://gist.github.com/kphretiq/e2f924416a326895233d

基本上,它会在每个表格上显示“SHOW TABLES”,然后是“DESCRIBE”,然后将其作为降价点出来。

只需在“if name”下面编辑即可。你需要安装pymysql。


3
投票

用一些可读的PHP捎带尼古拉的回答

$a = mysqli_query($conn,"select * from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position");
$b = mysqli_fetch_all($a,MYSQLI_ASSOC);
$d = array();
foreach($b as $c){
    if(!is_array($d[$c['TABLE_NAME']])){
        $d[$c['TABLE_NAME']] = array();
    }
    $d[$c['TABLE_NAME']][] = $c['COLUMN_NAME'];
}
echo "<pre>",print_r($d),"</pre>";
© www.soinside.com 2019 - 2024. All rights reserved.