问题:SQLAlchemy IN子句

我正在尝试在sqlalchemy中执行此查询

SELECT id, name FROM user WHERE id IN (123, 456)

我想[123, 456]在执行时绑定列表。

I’m trying to do this query in sqlalchemy

SELECT id, name FROM user WHERE id IN (123, 456)

I would like to bind the list [123, 456] at execution time.


回答 0

怎么样

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

编辑:没有ORM,它将是

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

需要两个参数,第一个是要检索的字段列表,第二个是where条件。您可以通过c(或columns)属性访问表对象上的所有字段。

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.


回答 1

假设您使用声明式样式(即ORM类),则非常简单:

query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()

db_session是您的数据库会话,User而是__tablename__等于的ORM类"users"

Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:

query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()

db_session is your database session here, while User is the ORM class with __tablename__ equal to "users".


回答 2

另一种方法是将原始SQL模式与SQLAlchemy结合使用,我使用SQLAlchemy 0.9.8,python 2.7,MySQL 5.X和MySQL-Python作为连接器,在这种情况下,需要一个元组。我的代码如下:

id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()

希望一切对您有用。

An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below:

id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()

Hope everything works for you.


回答 3

使用表达式API(基于注释就是这个问题的要求),您可以使用in_相关列的方法。

查询

SELECT id, name FROM user WHERE id in (123,456)

myList = [123, 456]
select = sqlalchemy.sql.select([user_table.c.id, user_table.c.name], user_table.c.id.in_(myList))
result = conn.execute(select)
for row in result:
    process(row)

这假定user_table并且conn已经适当定义。

With the expression API, which based on the comments is what this question is asking for, you can use the in_ method of the relevant column.

To query

SELECT id, name FROM user WHERE id in (123,456)

use

myList = [123, 456]
select = sqlalchemy.sql.select([user_table.c.id, user_table.c.name], user_table.c.id.in_(myList))
result = conn.execute(select)
for row in result:
    process(row)

This assumes that user_table and conn have been defined appropriately.


回答 4

只是想与我在python 3中使用sqlalchemy和pandas共享我的解决方案。也许,有人会觉得它有用。

import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]   
query = sa.text(""" 
                SELECT *
                FROM my_table
                WHERE col1 IN :values; 
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)

Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.

import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]   
query = sa.text(""" 
                SELECT *
                FROM my_table
                WHERE col1 IN :values; 
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)

回答 5

只是上述答案的补充。

如果要使用“ IN”语句执行SQL,则可以执行以下操作:

ids_list = [1,2,3]
query = "SELECT id, name FROM user WHERE id IN %s" 
args = [(ids_list,)] # Don't forget the "comma", to force the tuple
conn.execute(query, args)

两点:

  • IN语句不需要括号(例如“ … IN(%s)”),只需输入“ … IN%s”
  • 强制将ID列表作为元组的一个元素。别忘了“,”:(ids_list,)

编辑请 注意,如果列表的长度为一或零,则将引发错误!

Just an addition to the answers above.

If you want to execute a SQL with an “IN” statement you could do this:

ids_list = [1,2,3]
query = "SELECT id, name FROM user WHERE id IN %s" 
args = [(ids_list,)] # Don't forget the "comma", to force the tuple
conn.execute(query, args)

Two points:

  • There is no need for Parenthesis for the IN statement(like “… IN(%s) “), just put “…IN %s”
  • Force the list of your ids to be one element of a tuple. Don’t forget the ” , ” : (ids_list,)

EDIT Watch out that if the length of list is one or zero this will raise an error!


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。