首页 > 解决方案 > 如何显示一次表名并显示各个表的所有列名?

问题描述

我能够将所有表名及其各自的列显示为:

SNO Tables in Database  Column names 
1        table1               a
2        table1               b
3        table2               c
4        table2               d

哪个html文件是:

<html>
<head><link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}"></head>
<body>
<div>
<table border="1" align="center" class="w3-table w3-striped">
    <caption><strong>Farm Automation Details</strong></caption>
  <thead>
    <tr>
      <th>SNO</th>
      <th style="text-align:center">Tables in Database</th>
      <th style="text-align:center">Column names</th>
    </tr>
  </thead>
  <tbody>
  {%for row in result%}
    <tr>
      <td></td>
        <td style="text-align:center">{{ row[0] }}</td>
      <td style="text-align:center">{{ row[1] }} </td>
    </tr>
  {%endfor%}
</table>
</div>
</body>
</html>

并获取我写的表和列名:

sql="select table_name,column_name from information_schema.columns where table_schema = 'farmautomation' order by table_name,ordinal_position"
cursor.execute(sql)
result = cursor.fetchall()

我期望将表格显示为:

SNO Tables in Database  Column names 
1        table1              a,b
2        table2              c,d

我尝试在 table_name 上进行分组,但没有成功,请问我该如何显示如上?如何显示一次表名并显示各个表的所有列名?

标签: pythonhtmlpython-3.x

解决方案


您要使用的是 GROUP_CONCAT 函数:

select table_name, group_concat(column_name order by column_name asc) as column_names
    from information_schema.columns
    where table_schema = 'farmautomation'
    group by table_name
    ;

推荐阅读