【问题标题】:SQLAlchemy: SQL Expression with multiple where conditionsSQLAlchemy:具有多个 where 条件的 SQL 表达式
【发布时间】:2012-02-23 21:18:35
【问题描述】:

我在编写 SQLAlchemy Core 中的简单 SQL 更新语句时遇到了困难。但是,我找不到任何说明如何组合多个 where 条件的文档、示例或教程。我确定它在那里 - 只是找不到。

这是桌子:

self.struct    = Table('struct',
                     metadata,
                     Column('schema_name',         String(40),  nullable=False,
                                                                primary_key=True),
                     Column('struct_name',         String(40),  nullable=False,
                                                                primary_key=True),
                     Column('field_type',          String(10),  nullable=True),
                     Column('field_len',           Integer,     nullable=True) )

下面是插入和更新语句:

def struct_put(self, **kv):
   try:
       i = self.struct.insert()
       result = i.execute(**kv)
   except exc.IntegrityError:   # row already exists - update it:
       u = self.struct.update().\
           where((self.struct.c.struct_name==kv['struct_name']
                  and self.struct.c.schema_name==kv['schema_name'])).\
           values(field_len=kv['field_len'],
                  field_type=kv['field_type'])
       result = u.execute()

代码可以很好地处理插入,但会更新表中的所有行。你能帮我理解这个 where 子句的语法吗?欢迎提出所有建议 - 提前致谢。

编辑:更正后的子句如下所示:

        where((and_(self.struct.c.parent_struct_name==kv['parent_struct_name'],
                    self.struct.c.struct_name==kv['struct_name'],
                    self.struct.c.schema_name==kv['schema_name']))).\

这是一个非常简单的语法,但考虑到 SQLAlchemy 的许多层,很难确定在此上下文中究竟应用了什么。

【问题讨论】:

  • 使用 and_() 的捷径是将多个 where() 子句链接在一起。所以:.where(a==1).where(b==2).where(c==3)。见docs
  • 这可能也有帮助:from sqlalchemy import and_

标签: python sqlalchemy


【解决方案1】:

在我看来,您正在使用 Python 的“and”操作,它只会计算出围绕它的一个子句。您应该尝试使用 SQLAlchemy 中的“and_”函数。将这两个子句放在“and_”函数中。

【讨论】:

  • 啊,我想答案就这么简单。我在教程或其他任何地方都找不到这方面的任何例子。描述了函数,但我不清楚这是我将使用它们的地方。谢谢。
【解决方案2】:

在 SQLAlchemy 中,tablename.c 是一个特殊值,您在构造将由 SQLAlchemy 在运行时处理的条件时使用。

在这种特殊情况下,您只是说“更新名为 struct_name 的列与传入 struct_put(struct_name="struct_value", schema_name="schema_value") 的值匹配的所有行,并且名为 schema_name 的列与传入为 @987654325 的值匹配@。

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 2016-12-28
    • 2019-09-16
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多