您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關 SQLAlchemy的查詢語法有哪些,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
#簡單查詢
print(session.query(User).all())
print(session.query(User.name, User.fullname).all())
print(session.query(User, User.name).all())
#帶條件查詢
print(session.query(User).filter_by(name='user1').all())
print(session.query(User).filter(User.name == "user").all())
print(session.query(User).filter(User.name.like("user%")).all())
#多條件查詢
print(session.query(User).filter(and_(User.name.like("user%"), User.fullname.like("first%"))).all())
print(session.query(User).filter(or_(User.name.like("user%"), User.password != None)).all())
#sql過濾
print(session.query(User).filter("id>:id").params(id=1).all())
#關聯查詢
print(session.query(User, Address).filter(User.id == Address.user_id).all())
print(session.query(User).join(User.addresses).all())
print(session.query(User).outerjoin(User.addresses).all())
#聚合查詢
print(session.query(User.name, func.count('*').label("user_count")).group_by(User.name).all())
print(session.query(User.name, func.sum(User.id).label("user_id_sum")).group_by(User.name).all())
#子查詢
stmt = session.query(Address.user_id, func.count('*').label("address_count")).group_by(Address.user_id).subquery()
print(session.query(User, stmt.c.address_count).outerjoin((stmt, User.id == stmt.c.user_id)).order_by(User.id).all())
#exists
print(session.query(User).filter(exists().where(Address.user_id == User.id)))
print(session.query(User).filter(User.addresses.any()))
以下為映射類:
class User(Base):
__tablename__ = "users"
id = Column("id", Integer, primary_key=True)
name = Column("name", String)
fullname = Column("fullname", String)
password = Column("password", String)
addresses = relation("Address", order_by="Address.id", backref="user")
def __init__(self, id=None, name=None, fullname=None, password=None, addresses=[]):
self.id = id
self.name = name
self.fullname = fullname
self.password = password
self.addresses = addresses
def __repr__(self):
return "<User '{name}' '{fullname}' '{password}' {addresses}>".format(name=self.name, fullname=self.fullname, password=self.password, addresses=self.addresses)
class Address(Base):
__tablename__ = "address"
id = Column(Integer, primary_key=True)
email_address = Column(String, nullable=False)
user_id = Column(Integer, ForeignKey("users.id"))
#user = relation("User", backref="addresses", order_by="Address.id")
def __init__(self, email_address=None):
self.email_address = email_address
def __repr__(self):
return "<Address ({email_address}) user={user}>".format(email_address=self.email_address, user=self.user.name)
上述就是小編為大家分享的 SQLAlchemy的查詢語法有哪些了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。