models.py 里这么定义的
class Var(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(20))
time = db.Column(db.Integer)
......
现在假设有这么几个数据
| id | name | time |
| 1 | a | 1500016227 |
| 2 | a | 1500016237 |
| 3 | b | 1500016227 |
| 4 | b | 1500016237 |
| 5 | c | 1500016216 |
| 6 | c | 1500016226 |
原来单独获得某一个 name 的最新几条,返回不同 name 就多次查询。
model = Var.query.filter_by(name).order_by(Var.time.desc()).limit(1).all()
现在需要同时获得几个 name 的最新几条,比如上面的数据中,同时获得 b 和 c 的最新一条数据,应该让其返回 id 为 4 和 6 两条。
试了 distinct 和 group_by,前面只能写成 db.session.query(Var.name).group_by(Var.name),这样还得再循环单独查询后添加到列表里去。请问有没有什么好的方法?
8 条回复 • 2018-09-13 19:08:33 +08:00
|
1
Stitch 2017 年 7 月 14 日
这样
model = Var.query.filter_by(Var.name.in_(list_of_name)).order_by(Var.time.desc()).all() 参考: https://stackoverflow.com/questions/29326297/sqlalchemy-filter-by-field-in-list-but-keep-original-order |
|
2
yakumo17 OP @Stitch 这样的话,list_of_name 里包括 b,c 时,会得到 id 为 3,4,5,6 共 4 条结果,而不是两条。如果在后面加 limit(2)的话,会得到 3,4 两条结果,不能得到需要的 4,6 两条。
前面有其他可选的筛选条件,不一定直接提供查询哪些 name,所以我需要从筛选结果中来获得到底有几个 name。 set 那一步遍历了整个之前的结果,如果直接筛选条件少,返回结果多,这一步时间就会特长。 name_list = set((m.name for m in query)) models = [model for name in name_list for model in query.filter(Var.name == name).limit(limit).all() ] |
|
3
zrq495 2017 年 7 月 14 日
|
|
4
wingyiu 2017 年 7 月 14 日
a=select max(id), name from var group by name;
ids = [x.id for x in a] select id, name, time from var where id in $ids |
|
5
flniu 2017 年 7 月 14 日
如果 DBMS 支持 window function 和 over 子句,可以用 zrq495 回复的方法。( Postgres, Oracle, SQL Server )
如果 DBMS 支持 cross apply,也可以。 MySQL 的话: 1. 循环处理,取每个 name 的最新几条。(适用循环项不多的情况) 2. 取出所有数据,在 Python 中取最新几条。(适用总数据量不多的情况) 3. group by 出每个 name 的最新时间,再 join 取最新一条数据。(只能取最新一条,而且若时间有重复还需要去重) 没想到更好的方法了。 |
|
8
niklause 2018 年 9 月 13 日
最后写出来了吗?求答案
|
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide