python sqlalchemy 针对数据库json的查询 及 Exists
sqlalchemy 存在功能描述
names = ["aaa", "bbb", "hjuhyg",...]
session.query(User).filter(User.name.in_(names)) 当数据量很大时,查询速度会很慢,
所以想要优化mysql 的 in 查询时,可以使用exists,在 python中,一种方便的方法如下:
可以将查询转换为EXISTS格式的EXISTS子查询(SELECT 1 FROM ... WHERE ...)。
q = session.query(User).filter(User.name == 'fred')
session.query(q.exists())
生成类似于的SQL:
SELECT EXISTS (
SELECT 1 FROM users WHERE users.name = :name_1
) AS anon_1
EXISTS构造通常在WHERE子句中使用:
session.query(User.id).filter(q.exists()).scalar()
请注意,某些数据库(如SQL Server)不允许EXISTS表达式出现在SELECT的columns子句中。要基于exists作为WHERE选择一个简单的布尔值,请使用literal():
from sqlalchemy import literal
session.query(literal(True)).filter(q.exists()).scalar()
以上方法使用sql语句为:select num from a where num in(select num from b)用下面的语句替换:select num from a where exists(select 1 from b where num=a.num)
针对查询条件为json 或 arry
json我们可以使用如下方法:
如:labels= [{"key":"sxdc","value":"cderfe"},......],events.filter(EventModel.labels.contains(labels[0]), EventModel.labels.contains(labels[1])).all()
filter_labels = ""
for index in range(len(labels)):
filter_labels += EventModel.labels.contains(labels[index])
if index != len(labels) - 1:
filter_labels += ","
filter_labels = or_(filter_labels)
events = events.filter(filter_labels)
同理arry: names = ["aaa", "bbb", "hjuhyg",...]
filter_namels = ""
for index in range(len(names)):
filter_names += EventModel.names == (names[index])
if index != len(labels) - 1:
filter_labels += ","
filter_names = or_(filter_names)
events = events.filter(filter_names)
所有评论(0)