轉自:http://blog.csdn.net/shudaqi2010/article/details/51568219sql
幾種常見sqlalchemy查詢:
#簡單查詢
print(session.query(User).all())
print(session.query(User.name, User.fullname).all())
print(session.query(User, User.name).all()) session
#帶條件查詢
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()) .net
#多條件查詢
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()) blog
#sql過濾
print(session.query(User).filter("id>:id").params(id=1).all()) sqlalchemy
#關聯查詢
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()) it
#聚合查詢
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()) io
#子查詢
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()) import
#exists
print(session.query(User).filter(exists().where(Address.user_id == User.id)))
print(session.query(User).filter(User.addresses.any()))date
限制返回字段查詢
person = session.query(Person.name, Person.created_at,Person.updated_at).filter_by(name="zhongwei").order_by(Person.created_at).first()im
記錄總數查詢:from sqlalchemy import func# count User records, without# using a subquery.session.query(func.count(User.id))# return count of user "id" grouped# by "name"session.query(func.count(User.id)).\ group_by(User.name)from sqlalchemy import distinct# count distinct "name" valuessession.query(func.count(distinct(User.name)))