如何使用 SQLAlchemy 获取与三元组条件列表匹配的行
拥有 3 元组列表:
[(a, b, c), (d, e, f)]
我想从表中检索 3 列与元组匹配的所有行。对于此示例,查询 WHERE
子句可能如下所示:
(column_X = a AND column_Y = b AND column_Z = c)
OR (column_X = d AND column_Y = e AND column_Z = f)
How can I create such a request using SQLAlchemy ?就我而言,三元组列表将包含数百个元素,我正在寻找最佳的可扩展解决方案。
感谢您的帮助,
Having a list of 3-tuples :
[(a, b, c), (d, e, f)]
I want to retrieve all the rows from a table where 3 columns matches the tuples. FOr this example, the query WHERE
clause could be something like this :
(column_X = a AND column_Y = b AND column_Z = c)
OR (column_X = d AND column_Y = e AND column_Z = f)
How can I create such a request using SQLAlchemy ? In my case the 3-tuples list will contains hundred of elements, and I'm looking for the best scallable solution.
Thanks for your help,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法是使用 SQLAlchemy 提供的 tuple_ 函数:
这适用于 PostgreSQL,但不适用于 SQLite。不确定其他数据库引擎。
幸运的是,有一种适用于所有数据库的解决方法。
首先使用
and_
表达式映射所有项目:然后创建一个包含所有条件的
or_
过滤器:这是一个简单的示例:
哪个输出:
Easiest way would be using SQLAlchemy-provided tuple_ function:
This works with PostgreSQL, but breaks with SQLite. Not sure about other database engines.
Fortunately there's a workaround that should work on all databases.
Start by mapping out all the items with the
and_
expression:And then create an
or_
filter that encloses all the conditions:Here's a simple example:
Which outputs:
我怀疑可以很好地扩展的一种不太传统的方法是创建所有元组的临时表,然后加入该表:
它执行 SQL 如下:
A less conventional approach that I suspect would scale well would be to create a temporary table of all your tuples and then join on that:
which executes SQL like this:
有人会考虑在原始表中创建一个额外的键吗?
即用“1”-“2”-“3”创建一个新列而不是另一个表并检查唯一性。
Would anyone consider creating an extra key in the original table ?
i.e. create a new column with "1"-"2"-"3" instead of another table and check for the uniqueness.