我想做一個資料庫操作,我有 2 個表(Table1 和 Table2)。表 1 中有一個“id”列,表 2 中有 4 列(id、服務器、埠、端點)。所以我想比較兩個表的 id,如果匹配,我想要服務器、埠和端點的詳細資訊。我正在使用帶有 sqlalchemy 的 fastAPI。
模型檔案是這樣的
#Table1
class RD(Base):
__tablename__ = "table1"
id = Column(String, unique=True, index=True, nullable=False)
#Table2
class AD(Base):
__tablename__ = "table2"
id = Column(String, unique=True, index=True, nullable=False)
server = Column(String(100), index=True, nullable=False)
port = Column(String, index=True, nullable=False)
endpoint = Column(String, index=True, nullable=False)
現在我想要兩個表的 id,如果匹配,我想從表 2 中列印服務器、埠和端點。我也不想寫一個原始的 sql 查詢。我想寫一個基于 ORM 的查詢。
我的資料庫連接檔案
謝謝。
uj5u.com熱心網友回復:
我對您的代碼進行了一些修改,因為幾行在 id 列定義和 table1 name("response") 處給了我一個錯誤
class Table1(Base):
__tablename__ = "table1"
id = Column(String, primary_key=True, index=True)
class Table2(Base):
__tablename__ = "table2"
id = Column(String, primary_key=True, index=True)
server = Column(String(100), index=True, nullable=False)
port = Column(String, index=True, nullable=False)
endpoint = Column(String, index=True, nullable=False)
# Insert few rows in tables
db.add(Table1(id=1))
db.add(Table1(id=2))
db.add(Table1(id=3))
db.add(Table2(id=1, server='localhost', port=8000, endpoint='/home'))
db.add(Table2(id=2, server='localhost', port=8000, endpoint='/cart'))
db.add(Table2(id=5, server='localhost', port=8000, endpoint='/item'))
db.commit()
現在當我執行這個查詢時:
result = db.query(Table2).filter(Table1.id == Table2.id).all()
for row in result:
print(row.server, row.port, row.endpoint)
我從 table2 中獲得了 id 等于表 1 中的 id 的行
localhost 8000 /home
localhost 8000 /cart
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410112.html
標籤:
上一篇:在組sql中過濾結果
