【问题标题】:How to show the table name once and show all column names of respective table?如何显示一次表名并显示各个表的所有列名?
【发布时间】:2019-08-27 07:38:15
【问题描述】:

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

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 上进行分组,但没有成功,请问我该如何显示如上? 如何显示表名一次,并显示各个表的所有列名?

【问题讨论】:

  • 我认为可能有一种方法可以直接在 SQL 中使用COALESCE 对结果进行分组(也许看看here)但最简单的方法是循环result 并创建一个看起来像 { table1: [a, b] } 的字典,然后在您的 Jinja2 (?) 模板中使用这个字典。您可以在 HTML 中使用{{ loop.index }} 添加SNO
  • 有点糊涂,能详细点吗?

标签: python html python-3.x


【解决方案1】:

你要使用的是 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
    ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-07
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多