最近工作中,有同学在问sqlalchemy的使用。当我和他详细了解后,发现属于Sqlalchemy的高阶使用,所以整理了这篇文章,以记录SqlAlchemy的部分高阶用法,本篇讲到的主要是搜索查询。
sql = "select count(*) as num, address from soufang where address like '%{}%' group by address order by num DESC limit 9".format(kw)
1.先实现简单查询
select * from soufang
SouFang.query
2.修改为获取 count() 获取数量 ,获取address字段
select count(*) as num, address from soufang
from sqlalchemy import func
kw = ''
Soufang.query.with_entities(func.count(), SouFang.address)
3. 添加 根据kw进行过滤
select count(*) as num, address from soufang where address like '%{}%'.format(kw)
from sqlalchemy import func
kw = ''
Soufang.query.with_entities(func.count(), SouFang.address).filter(SouFang.address.contains(kw))
4. 添加 根据address进行分组
select count(*) as num, address from soufang where address like '%{}%' group by address
from sqlalchemy import func
kw = ''
Soufang.query.with_entities(func.count(), SouFang.address).filter(SouFang.address.contains(kw)).group_by(Soufang.address)
5. 添加 根据数量进行排序,倒序
select count(*) as num, address from soufang where address like '%{}%' group by address order by num DESC
from sqlalchemy import func
kw = ''
SouFang.query.with_entities(func.count(), SouFang.address).filter(SouFang.address.contains(kw)).group_by(Soufang.address).order_by(desc('num'))
6. 添加 限制获取数量 limit()
select count(*) as num, address from soufang where address like '%{}%' group by address order by num DESC limit 9
from sqlalchemy import func
kw = ''
SouFang.query.with_entities(func.count(), SouFang.address).filter(SouFang.address.contains(kw)).group_by(Soufang.address).order_by(desc('num')).limit(9)
5