SQLAlchemy操作MariaDB笔记之三

查询语法练习

query方法返回的是一个可迭代输出的对象,可以索引和切片。参数可以为表对象,表的字段对象。

>>> for instance in session.query(User).order_by(User.id): 
...     print instance.name, instance.fullname
>>> for name, fullname in session.query(User.name, User.fullname): 
...     print name, fullname

给表对象起别名,同时可以指定字段的别名

>>> from sqlalchemy.orm import aliased
>>> user_alias = aliased(User, name='user_alias')

SQL>>> for row in session.query(user_alias, user_alias.name).all(): 
...    print row.user_alias

fillter_by()方法相当于where子句;order_by
方法相当于orderby子句;

子句中的符号:

query.filter(User.name == ‘ed’)

query.filter(User.name != ‘ed’)

LIKE

query.filter(User.name.like(‘%ed%’))

IN

query.filter(User.name.in_([‘ed’, ‘wendy’, ‘jack’]))

从句

query.filter(User.name.in_(
session.query(User.name).filter(User.name.like(‘%ed%’))
))

NOT IN

query.filter(~User.name.in_([‘ed’, ‘wendy’, ‘jack’]))

IS NULL

query.filter(User.name == None)

AND

from sqlalchemy import and_

query.filter(and_(User.name == ‘ed’, User.fullname == ‘Ed Jones’))

query.filter(User.name == ‘ed’, User.fullname == ‘Ed Jones’)

OR

query.filter(User.name == ‘ed’).filter(User.fullname == ‘Ed Jones’)

from sqlalchemy import or_
query.filter(or_(User.name == ‘ed’, User.name == ‘wendy’))

MATCH

query.filter(User.name.match(‘wendy’))

你可能感兴趣的:(SQLAlchemy操作MariaDB笔记之三)