取得MySQL中所有表格的列名和最後一筆記錄
P粉401527045
P粉401527045 2024-03-31 13:15:35
0
1
346

有沒有辦法取得所有表的最新值及其列名,而不是選擇每個表。我遇到了以下選擇查詢,但它只返回列名稱,如果我使用 * 而不是 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學習者快速成長!