1. 程式人生 > >SQLAlchemy教程(三)複雜查詢

SQLAlchemy教程(三)複雜查詢

這章節要操作的資料 

 多條件查詢,可以在表示式中各種and,ro方式進行查詢

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

row1 = session.query(models.Users).filter(text("nid>:value or age>:age")).params(value=9,age=30).all()
row_list = [row.name for row in row1]
print(row_list)

try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['警皇', '豬皇', '沙加特', '春麗', '桑切爾夫', '隆', '肯', '豪鬼', '骨裂']

between函式,查詢某一列和某一列之間的資料

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

row1 = session.query(models.Users).filter(models.Users.name.between('春麗','骨裂')).all()
row_list = [row.name for row in row1]
print(row_list)
try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['春麗', '桑切爾夫', '沙加特', '豬皇', '肯', '警皇', '豪鬼', '阿比蓋爾', '隆', '骨裂']

查詢包含與不包含

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

#包含nid為8,9
row1 = session.query(models.Users).filter(models.Users.nid.in_([8,9])).all()
row_list = [row.name for row in row1]
print(row_list)

#不包含nid為8,9
row1 = session.query(models.Users).filter(~models.Users.nid.in_([8,9])).all()
row_list = [row.name for row in row1]
print(row_list)

try:
    session.commit()
except Exception as e:
    print(e)
session.close()

#結果

['警皇', '豬皇']
['阿比蓋爾', '嘉米', '小櫻02', '勞拉02', '沙加特', '春麗', '桑切爾夫', '隆', '肯', '豪鬼', '骨裂']

查詢巢狀

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
#獲取年齡等於35的使用者id,再通過包含查詢,查詢到這兩個id的資料
row1 = session.query(models.Users).filter(models.Users.nid.in_(session.query(models.Users.nid).filter(models.Users.age==35))).all()
row_list = [row.name for row in row1]
print(row_list)

try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['桑切爾夫', '骨裂']

上面說到了使用or,and的用法,但只是編寫表示式,並不是面向物件

下面示例是使用面向物件的方式

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models
from sqlalchemy import and_,or_

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()


#查詢nid大於9,年齡小於30的使用者
row1 = session.query(models.Users).filter(and_(models.Users.nid>9,models.Users.age<30))
row_list = [row.name for row in row1]
print(row_list)

#查詢gender是真的使用者,或者年齡小於30的使用者
row1 = session.query(models.Users).filter(or_(models.Users.gender==True,models.Users.age<30))
row_list = [row.name for row in row1]
print(row_list)

#and_和or_可以互相巢狀,查詢gender是真的使用者,或者id>1而且年齡在20到30之間
row1 = session.query(models.Users).filter(
    or_(
        models.Users.gender==True,
        and_(
            models.Users.nid>1,
            models.Users.age.between(20,30)
        )
    )
).all()
row_list = [row.name for row in row1]
print(row_list)


try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['春麗', '肯']
['阿比蓋爾', '嘉米', '小櫻02', '勞拉02', '春麗', '肯']
['嘉米', '小櫻02', '勞拉02', '春麗', '隆', '肯']

分頁

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models
from sqlalchemy import and_,or_

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

#offset:起始位置
#limit:數量
row1 = session.query(models.Users).offset(2).limit(3)
row_list = [row.name for row in row1]
print(row_list)

try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['小櫻02', '勞拉02', '警皇']

模糊查詢

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models
from sqlalchemy import and_,or_

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

#查詢年齡3字頭的使用者
row1 = session.query(models.Users).filter(models.Users.age.like("3%")).all()
row_list = [row.name for row in row1]
print(row_list)

try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['勞拉02', '豬皇', '桑切爾夫', '隆', '骨裂']

排序

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from s1 import models
from sqlalchemy import and_,or_

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

#按照年齡排序
#升序
row1 = session.query(models.Users).order_by(models.Users.age.asc())
row_list = [row.name for row in row1]
print(row_list)
#降序
row1 = session.query(models.Users).order_by(models.Users.age.desc())
row_list = [row.name for row in row1]
print(row_list)
try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
['阿比蓋爾', '嘉米', '小櫻02', '春麗', '肯', '勞拉02', '隆', '桑切爾夫', '骨裂', '豬皇', '沙加特', '豪鬼', '警皇']
['警皇', '沙加特', '豪鬼', '豬皇', '桑切爾夫', '骨裂', '勞拉02', '隆', '肯', '春麗', '小櫻02', '嘉米', '阿比蓋爾']

聚合函式

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text, func
from s1 import models
from sqlalchemy import and_, or_

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

# 聚合
ret = session.query(
    func.sum(models.Users.age), # 所有數相加的值
    func.max(models.Users.age), #最大值
    func.min(models.Users.age) #最小值
).first()
print(ret)

try:
    session.commit()
except Exception as e:
    print(e)

session.close()

分組

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.sql import text, func
from s1 import models
from sqlalchemy import and_, or_

engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()

#分組
ret = session.query(func.count(models.Users.name)).group_by(models.Users.gender).all()
print('男:',ret[0][0],'個')
print('女:',ret[1][0],'個')
try:
    session.commit()
except Exception as e:
    print(e)

session.close()

#結果
男: 9 個
女: 4 個