获取MySQL中所有表的列名和最后一条记录
P粉401527045
P粉401527045 2024-03-31 13:15:35
0
1
348

有没有办法获取所有表的最新值及其列名,而不是选择每个表。我遇到了以下选择查询,但它只返回列名称,如果我使用 * 而不是 column_name,则有很多我不需要的不必要的详细信息。

SELECT column_name 
FROM information_schema.columns 
where table_schema = 'classicmodels'  
order by table_name, ordinal_position

我只需要包含该列中最新记录的列名称。

P粉401527045
P粉401527045

全部回复(1)
P粉211273535

我可以使用 phyton sql 连接器读取所有表的最新记录。可能有更好的方法来做到这一点,但因为我不允许在正在运行的数据库中工作,所以我选择了这种方法。

import logging
import mysql.connector

mydb = mysql.connector.connect(
    host="127.0.0.1",
    port=3306,
    user="root",
    password="root",
    database="classicmodels")

mycursor = mydb.cursor(buffered=True , dictionary=True)

sql = "SELECT * FROM information_schema.tables where table_schema = 'classicmodels'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
tables = [d['TABLE_NAME'] for d in myresult]

for x in tables:
    sql1 = "select * from {}".format(x)
    mycursor.execute(sql1)
    myresult1 = mycursor.fetchone()
    for val, cal in myresult1.items():
        print(f'{val} is {cal}')
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!