版本:1.1.0b2 |发布日期:2016年7月1日

SQLAlchemy 1.1文档

Selectables,Tables,FROM objects

The term “selectable” refers to any object that rows can be selected from; in SQLAlchemy, these objects descend from FromClause and their distinguishing feature is their FromClause.c attribute, which is a namespace of all the columns contained within the FROM clause (these elements are themselves ColumnElement subclasses).

sqlalchemy.sql.expression.alias(selectable, name=None, flat=False)

返回一个Alias对象。

An Alias represents any FromClause with an alternate name assigned within SQL, typically using the AS clause when generated, e.g. SELECT * FROM table AS aliasname.

类似的功能可以通过所有FromClause子类上的alias()方法使用。

当从Table对象创建Alias时,这会使表格呈现为tablename AS < / t8> aliasname

For select() objects, the effect is that of creating a named subquery, i.e. (select ...) AS aliasname.

name参数是可选的,并提供在呈现的SQL中使用的名称。如果为空,则会在编译时确定性地生成“匿名”名称。确定性意味着该名称对于在同一语句中使用的其他构造是唯一的,并且对于同一个语句对象的每个连续编译也将是相同的名称。

参数:
  • selectable – any FromClause subclass, such as a table, select statement, etc.
  • name – string name to be assigned as the alias. 如果None,则会在编译时确定性地生成名称。
  • flat -

    如果给定的selectable是Join的实例,请参阅Join.alias()以获取详细信息。

    版本0.9.0中的新功能

sqlalchemy.sql.expression.except_(*selects, **kwargs)

返回多个可选项的EXCEPT

返回的对象是CompoundSelect的一个实例。

*选择
Select实例列表。
** kwargs
可用的关键字参数与select()相同。
sqlalchemy.sql.expression.except_all(*selects, **kwargs)

返回多个可选项的EXCEPT ALL

返回的对象是CompoundSelect的一个实例。

*选择
Select实例列表。
** kwargs
可用的关键字参数与select()相同。
sqlalchemy.sql.expression.exists(*args, **kwargs)

针对现有的Select对象构建新的Exists

调用样式具有以下形式:

# use on an existing select()
s = select([table.c.col1]).where(table.c.col2==5)
s = exists(s)

# construct a select() at once
exists(['*'], **select_arguments).where(criterion)

# columns argument is optional, generates "EXISTS (SELECT *)"
# by default.
exists().where(table.c.col2==5)
sqlalchemy.sql.expression.intersect(*selects, **kwargs)

Return an INTERSECT of multiple selectables.

返回的对象是CompoundSelect的一个实例。

*选择
Select实例列表。
** kwargs
可用的关键字参数与select()相同。
sqlalchemy.sql.expression.intersect_all(*selects, **kwargs)

返回多个可选项的INTERSECT ALL

返回的对象是CompoundSelect的一个实例。

*选择
Select实例列表。
** kwargs
可用的关键字参数与select()相同。
sqlalchemy.sql.expression.join(left, right, onclause=None, isouter=False, full=False)

给定两个FromClause表达式,产生一个Join对象。

例如。:

j = join(user_table, address_table,
         user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id

Similar functionality is available given any FromClause object (e.g. such as a Table) using the FromClause.join() method.

参数:
  • left - 连接的左侧。
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join() - method form, based on a given left side

Join - 生成的对象的类型

sqlalchemy.sql.expression.lateral(selectable, name=None)

返回一个Lateral对象。

Lateral是一个Alias子类,它表示应用了LATERAL关键字的子查询。

LATERAL子查询的特殊行为是它出现在封闭SELECT的FROM子句中,但可能与该SELECT的其他FROM子句相关。这是子查询的一种特殊情况,只有少数后端支持,现在是更新的Postgresql版本。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

sqlalchemy.sql.expression.outerjoin(left, right, onclause=None, full=False)

返回一个OUTER JOIN子句元素。

返回的对象是Join的实例。

类似的功能也可以通过任何FromClause上的outerjoin()方法使用。

参数:
  • left - 连接的左侧。
  • - 连接的右侧。
  • onclause – Optional criterion for the ON clause, is derived from foreign key relationships established between left and right otherwise.

要将连接链接在一起,请在生成的Join对象上使用FromClause.join()FromClause.outerjoin()方法。

sqlalchemy.sql.expression.select(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)

构建一个新的Select

通过任何FromClause上的FromClause.select()方法也可以获得类似的功能。

接受ClauseElement参数的所有参数也接受字符串参数,这些参数将根据需要转换为text()literal_column()结构。

也可以看看

Selecting - select()的核心教程描述。

参数:
  • -

    ColumnElementFromClause对象的列表,这些对象将形成结果语句的列子句。For those objects that are instances of FromClause (typically Table or Alias objects), the FromClause.c collection is extracted to form a collection of ColumnElement objects.

    该参数还将接受给定的Text结构,以及ORM映射的类。

    注意

    select.columns参数在select()的方法形式中不可用,例如, FromClause.select()

  • whereclause -

    将用于形成WHERE子句的ClauseElement表达式。通常最好将WHERE标准添加到与Select.where()链接的现有Select使用方法中。

    也可以看看

    Select.where()

  • from_obj -

    将被添加到结果语句的FROM子句中的ClauseElement对象的列表。这相当于在现有的Select对象上使用方法链接调用Select.select_from()

    也可以看看

    Select.select_from() - full description of explicit FROM clause specification.

  • autocommit -

    已过时。使用.execution_options(autocommit=<True|False>)来设置自动提交选项。

  • bind=None – an Engine or Connection instance to which the resulting Select object will be bound. 否则Select对象将自动绑定到Connectable实例可以位于其包含的ClauseElement成员中的任何位置。
  • correlate = True -

    表明这个Select对象应该包含FromClause元素与一个封闭的Select对象“相关”。通常最好使用Select.correlate()指定现有Select构造上的相关性。

    也可以看看

    Select.correlate() - full description of correlation.

  • distinct = False -

    True时,将DISTINCT限定符应用于结果语句的columns子句。

    布尔参数也可以是列表达式或列表达式的列表 - 这是一种特殊的调用形式,Postgresql方言可以理解为DISTINCT ON (&lt; columns&gt;)语法。

    通过distinct()方法,现有的Select对象也可以使用distinct

    也可以看看

    Select.distinct()

  • for_update = False -
    True时,将FOR UPDATE应用到结果语句的末尾。

    Deprecated since version 0.9.0: - use Select.with_for_update() to specify the structure of the FOR UPDATE clause.

    for_update接受由特定后端解释的各种字符串值,包括:

    • "read" - on MySQL, translates to LOCK IN SHARE MODE; on Postgresql, translates to FOR SHARE.
    • "nowait" - on Postgresql and Oracle, translates to FOR UPDATE NOWAIT.
    • "read_nowait" - on Postgresql, translates to FOR SHARE NOWAIT.

    也可以看看

    Select.with_for_update() - improved API for specifying the FOR UPDATE clause.

  • group_by -

    将包含结果选择的GROUP BY子句的ClauseElement对象的列表。This parameter is typically specified more naturally using the Select.group_by() method on an existing Select.

    也可以看看

    Select.group_by()

  • -

    GROUP BY时,ClauseElement将包含结果选择的HAVING用来。此参数通常在现有Select中使用Select.having()方法更自然地指定。

    也可以看看

    Select.having()

  • 限制=无 -

    一个数值,通常在结果选择中呈现为LIMIT表达式。不支持LIMIT的后端将尝试提供类似的功能。此参数通常在现有的Select中使用Select.limit()方法来更自然地指定。

    也可以看看

    Select.limit()

  • 偏移量=无 -

    a numeric value which usually renders as an OFFSET expression in the resulting select. 不支持OFFSET的后端将尝试提供类似的功能。此参数通常在现有Select中使用Select.offset()方法更自然地指定。

    也可以看看

    Select.offset()

  • order_by -

    一个标量或ClauseElement对象的列表,它们将包含结果select的ORDER BY子句。此参数通常在现有的Select中使用Select.order_by()方法更自然地指定。

    也可以看看

    Select.order_by()

  • use_labels = False -

    True时,将使用columns子句中每列的标签生成该语句,该列使用其父表的名称(或别名)限定每个列,以便不同表中的列之间的名称冲突不会发生。标签的格式是_ 。 T1> T0>生成的Select对象的“c”集合也将使用这些名称来定位列成员。

    也可以使用Select.apply_labels()方法在现有的Select对象上指定此参数。

    也可以看看

    Select.apply_labels()

sqlalchemy.sql.expression。 子查询 tt> 别名* args ** kwargs T5> ) T6> ¶ T7>

返回从Select派生的Alias对象。

名称
别名

* args,** kwargs

所有其他参数传递给select()函数。
sqlalchemy.sql.expression.table(name, *columns)

产生一个新的TableClause

返回的对象是一个TableClause实例,它表示模式级别Table对象的“语法”部分。它可能被用来构造轻量级的表格结构。

Changed in version 1.0.0: expression.table() can now be imported from the plain sqlalchemy namespace like any other SQL element.

参数:
sqlalchemy.sql.expression.tablesample(selectable, sampling, name=None, seed=None)

返回一个TableSample对象。

TableSample is an Alias subclass that represents a table with the TABLESAMPLE clause applied to it. tablesample() is also available from the FromClause class via the FromClause.tablesample() method.

TABLESAMPLE子句允许从表中选择一个随机选择的近似百分比的行。它支持多种采样方法,最常见的是BERNOULLI和SYSTEM。

例如。:

from sqlalchemy import func

selectable = people.tablesample(
            func.bernoulli(1),
            name='alias',
            seed=func.random())
stmt = select([selectable.c.people_id])

假设people具有列people_id,则上述语句将呈现为:

SELECT alias.people_id FROM
people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
REPEATABLE (random())

版本1.1中的新功能

参数:
  • sampling – a float percentage between 0 and 100 or functions.Function.
  • 名称 - 可选的别名
  • seed – any real-valued SQL expression. 指定时,也会呈现REPEATABLE子句。
sqlalchemy.sql.expression.union(*selects, **kwargs)

返回多个可选择的UNION

返回的对象是CompoundSelect的一个实例。

所有FromClause子类都有一个类似的union()方法。

*选择
Select实例列表。
** kwargs
可用的关键字参数与select()相同。
sqlalchemy.sql.expression.union_all(*selects, **kwargs)

返回多个可选项的UNION ALL

返回的对象是CompoundSelect的一个实例。

所有FromClause子类中都有一个类似的union_all()方法。

*选择
Select实例列表。
** kwargs
可用的关键字参数与select()相同。
class sqlalchemy.sql.expression。 别名 可选名称=无 T5> ) T6> ¶ T7>

基础:sqlalchemy.sql.expression.FromClause

表示一个表或可选别名(AS)。

使用AS关键字(或在某些数据库(例如Oracle)上没有关键字),通常应用于SQL语句内的任何表或子选择,表示别名。

This object is constructed from the alias() module level function as well as the FromClause.alias() method available on all FromClause subclasses.

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

class sqlalchemy.sql.expression.CompoundSelect(keyword, *selects, **kwargs)

基础:sqlalchemy.sql.expression.GenerativeSelect

Forms the basis of UNION, UNION ALL, and other
基于SELECT的集合操作。
alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

append_group_by T0> ( T1> *条款 T2> ) T3> ¶ T4>

追加应用于此可选项的给定GROUP BY标准。

该标准将被附加到任何预先存在的GROUP BY标准。

这是一种in-place突变方法; group_by()方法是首选,因为它提供了标准的method chaining

append_order_by T0> ( T1> *条款 T2> ) T3> ¶ T4>

附加给定的ORDER BY标准应用于此可选项。

该标准将被附加到任何预先存在的ORDER BY标准。

这是一种in-place突变方法; order_by()方法是首选,因为它提供了标准的method chaining

apply_labels T0> ( T1> ) T2> ¶ T3>

返回一个新的可选项,并将'use_labels'标志设置为True。

这将导致使用标签对其表名称生成列表达式,例如“SELECT somecolumn AS tablename_somecolumn”。这允许包含多个FROM子句的可选项生成一组唯一的列名称,而不考虑各个FROM子句之间的名称冲突。

as_scalar T0> ( T1> ) T2> ¶ T3>
继承自 as_scalar() 方法 SelectBase

返回这个可选项的'标量'表示,它可以用作列表达式。

通常,在其子列中只有一列的select语句可以用作标量表达式。

返回的对象是ScalarSelect的一个实例。

自动提交 T0> ( T1> ) T2> ¶ T3>
继承自 autocommit() 方法 SelectBase

将'autocommit'标志设置为True返回一个新的可选项。

从版本0.6开始弃用: autocommit()已弃用。使用带有'autocommit'标志的Executable.execution_options()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

cte(name=None, recursive=False)
继承自 cte() 方法 HasCTE

返回一个新的CTE或公共表表达式实例。

公用表表达式是一种SQL标准,通过使用一个名为“WITH”的子句,SELECT语句可以使用与主语句一起指定的次要语句。有关UNION的特殊语义也可用于允许“递归”查询,其中SELECT语句可以在先前已选择的一组行上进行绘制。

CTE也可以应用于DML构造对某些数据库的UPDATE,INSERT和DELETE,与RETURNING一起作为CTE行的来源以及CTE行的使用者。

SQLAlchemy将CTE对象检测为与Alias对象类似的对象,作为要传递到语句的FROM子句的特殊元素以及顶部的WITH子句的声明。

在版本1.1中进行了更改:添加了对CTE,CTE添加到UPDATE / INSERT / DELETE的UPDATE / INSERT / DELETE的支持。

参数:
  • name – name given to the common table expression. _FromClause.alias()一样,名称可以保留为None,在这种情况下,查询编译时将使用匿名符号。
  • recursive – if True, will render WITH RECURSIVE. 递归公用表表达式旨在与UNION ALL结合使用,以便从已选择的行中派生行。

以下示例包含两篇来自Postgresql的文档,位于http://www.postgresql.org/docs/current/static/queries-with.html以及其他示例。

例1,非递归:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

例2,与RECURSIVE:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.sub_part,
        parts_alias.c.part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

例3,使用带CTE的UPDATE和INSERT的upsert:

orders = table(
    'orders',
    column('region'),
    column('amount'),
    column('product'),
    column('quantity')
)

upsert = (
    orders.update()
    .where(orders.c.region == 'Region1')
    .values(amount=1.0, product='Product1', quantity=1)
    .returning(*(orders.c._all_columns)).cte('upsert'))

insert = orders.insert().from_select(
    orders.c.keys(),
    select([
        literal('Region1'), literal(1.0),
        literal('Product1'), literal(1)
    ).where(exists(upsert.select()))
)

connection.execute(insert)

也可以看看

orm.query.Query.cte() - HasCTE.cte()的ORM版本。

描述 T0> ¶ T1>

这个FromClause的简要描述。

主要用于错误消息格式。

执行 tt> * multiparams** params T5>
继承自 execute() 方法 Executable

编译并执行Executable

execution_options T0> ( T1> **千瓦 T2> ) T3> ¶ T4>
继承自 execution_options() 方法 tt> Executable

为执行期间生效的语句设置非SQL选项。

执行选项可以在每个语句或每个Connection的基础上设置。此外,Engine和ORM Query对象提供对执行选项的访问,而这些执行选项在连接时进行配置。

execution_options()方法是生成的。返回此语句的新实例,其中包含以下选项:

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

请注意,只有一部分可能的执行选项可以应用于语句 - 这些选项包括“autocommit”和“stream_results”,但不包括“isolation_level”或“c​​ompiled_cache”。有关可能的选项的完整列表,请参阅Connection.execution_options()

FOR_UPDATE T0> ¶ T1>
继承自 for_update 属性 GenerativeSelect

for_update属性提供传统方言支持。

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

GROUP_BY T0> ( T1> *条款 T2> ) T3> ¶ T4>
group_by() 方法继承的GenerativeSelect

返回一个新的可选项,其中应用了GROUP BY标准的给定列表。

该标准将被附加到任何预先存在的GROUP BY标准。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

标签 T0> ( T1> 名称 T2> ) T3> ¶ T4>
继承自 label() 方法 SelectBase

返回这个可选择的“标量”表示,嵌入为带有标签的子查询。

也可以看看

as_scalar()

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

限制 T0> ( T1> 限制 T2> ) T3> ¶ T4>
inherited from the limit() method of GenerativeSelect

返回一个新的可选择的给定LIMIT标准。

这是一个数值,通常在结果选择中呈现为LIMIT表达式。不支持LIMIT的后端将尝试提供类似的功能。

版本1.0.0更改: - Select.limit()现在可以接受任意SQL表达式以及整数值。

参数:limit – an integer LIMIT parameter, or a SQL expression that provides an integer result.
偏移 T0> ( T1> 偏移 T2> ) T3> ¶ T4>
inherited from the offset() method of GenerativeSelect

使用给定的OFFSET标准返回一个新的可选项。

This is a numeric value which usually renders as an OFFSET expression in the resulting select. 不支持OFFSET的后端将尝试提供类似的功能。

版本1.0.0更改: - Select.offset()现在可以接受任意SQL表达式以及整数值。

参数:offset – an integer OFFSET parameter, or a SQL expression that provides an integer result.
ORDER_BY T0> ( T1> *条款 T2> ) T3> ¶ T4>
inherited from the order_by() method of GenerativeSelect

返回一个新的可选项,其中应用了ORDER BY标准的给定列表。

该标准将被附加到任何预先存在的ORDER BY标准。

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

标量 * multiparams** params T5>
inherited from the scalar() method of Executable

编译并执行此Executable,返回结果的标量表示。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

with_for_update(nowait=False, read=False, of=None, skip_locked=False, key_share=False)
inherited from the with_for_update() method of GenerativeSelect

GenerativeSelect指定一个FOR UPDATE子句。

例如。:

stmt = select([table]).with_for_update(nowait=True)

在像Postgresql或Oracle这样的数据库上,上面的代码会显示如下的语句:

SELECT table.a, table.b FROM table FOR UPDATE NOWAIT

在其他后端,nowait选项被忽略,而是产生:

SELECT table.a, table.b FROM table FOR UPDATE

当不带任何参数调用时,语句将以后缀FOR UPDATE进行呈现。然后可以提供其他参数,这些参数允许使用通用数据库特定的变体。

参数:
  • nowait - boolean;将在Oracle和Postgresql方言中呈现FOR tt> UPDATE NOWAIT
  • - boolean;将在MySQL上呈现LOCK IN SHARE 模式在Postgresql上共享 共享On Postgresql, when combined with nowait, will render FOR SHARE NOWAIT.
  • of – SQL expression or list of SQL expression elements (typically Column objects or a compatible expression) which will render into a FOR UPDATE OF clause; supported by PostgreSQL and Oracle. 可以根据后端呈现为表格或列。
  • skip_locked -

    boolean, will render FOR UPDATE SKIP LOCKED on Oracle and Postgresql dialects or FOR SHARE SKIP LOCKED if read=True is also specified.

    版本1.1.0中的新功能

  • key_share -

    boolean, will render FOR NO KEY UPDATE, or if combined with read=True will render FOR KEY SHARE, on the Postgresql dialect.

    版本1.1.0中的新功能

class sqlalchemy.sql.expression.CTE(selectable, name=None, recursive=False, _cte_alias=None, _restates=frozenset([]), _suffixes=None)

基础:sqlalchemy.sql.expression.Generativesqlalchemy.sql.expression.HasSuffixessqlalchemy.sql.expression.Alias

代表通用表达式。

CTE对象是使用任何可选择的SelectBase.cte()方法获得的。查看完整示例的方法。

New in version 0.7.6.

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

后缀 tt> * expr** kw T5>
inherited from the suffix_with() method of HasSuffixes

在整个语句后添加一个或多个表达式。

这用于在特定结构上支持后端特定的后缀关键字。

例如。:

stmt = select([col1, col2]).cte().suffix_with(
    "cycle empno set y_cycle to 1 default 0", dialect="oracle")

多个后缀可以通过多次调用suffix_with()来指定。

参数:
  • *expr – textual or ClauseElement construct which will be rendered following the target clause.
  • ** kw - 接受单个关键字'dialect'。这是一个可选的字符串方言名称,它将限制仅将该后缀渲染为该方言。
tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

class sqlalchemy.sql.expression。 可执行文件

基础:sqlalchemy.sql.expression.Generative

将一个ClauseElement标记为支持执行。

Executable is a superclass for all “statement” types of objects, including select(), delete(), update(), insert(), text().

结合 T0> ¶ T1>

返回此Executable绑定到的EngineConnection;如果没有找到,则返回None。

这是遍历,在本地进行检查,然后检查关联对象的“from”子句,直到找到绑定的引擎或连接。

执行 tt> * multiparams** params T5>

编译并执行Executable

execution_options T0> ( T1> **千瓦 T2> ) T3> ¶ T4>

为执行期间生效的语句设置非SQL选项。

执行选项可以在每个语句或每个Connection的基础上设置。此外,Engine和ORM Query对象提供对执行选项的访问,而这些执行选项在连接时进行配置。

execution_options()方法是生成的。返回此语句的新实例,其中包含以下选项:

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

请注意,只有一部分可能的执行选项可以应用于语句 - 这些选项包括“autocommit”和“stream_results”,但不包括“isolation_level”或“c​​ompiled_cache”。有关可能的选项的完整列表,请参阅Connection.execution_options()

标量 * multiparams** params T5>

编译并执行此Executable,返回结果的标量表示。

class sqlalchemy.sql.expression。 FromClause

基础:sqlalchemy.sql.expression.Selectable

表示可以在SELECT语句的FROM子句中使用的元素。

最常见的FromClause形式是Tableselect()结构。所有FromClause对象共有的主要特征包括:

alias(name=None, flat=False)

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

C T0> ¶ T1>

columns属性的别名。

列 T0> ¶ T1>

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
对等元等于 等值

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

描述 T0> ¶ T1>

这个FromClause的简要描述。

主要用于错误消息格式。

foreign_keys T0> ¶ T1>

返回FromClause引用的ForeignKey对象的集合。

is_derived_from T0> ( T1> fromclause T2> ) T3> ¶ T4>

如果FromClause从给定的FromClause中“派生”,则返回True。

一个例子是从表中派生的表的别名。

join(right, onclause=None, isouter=False, full=False)

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

primary_key T0> ¶ T1>

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

架构 =无

FromClause定义'schema'属性。

Table以外的大多数对象,这通常是None,它被视为Table.schema参数的值。

选择 whereclause = None** params / T5>

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

tablesample(sampling, name=None, seed=None)

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

class sqlalchemy.sql.expression.GenerativeSelect(use_labels=False, for_update=False, limit=None, offset=None, order_by=None, group_by=None, bind=None, autocommit=None)

基础:sqlalchemy.sql.expression.SelectBase

可以添加其他元素的SELECT语句的基类。

这可以作为SelectCompoundSelect的基础,其中可以添加ORDER BY,GROUP BY等元素,并且可以控制列呈现。TextAsFrom相比,它虽然它的子类为SelectBase,并且也是一个SELECT构造,它表示一个固定的文本字符串,不能在此级别进行更改,只能打包为子查询。

版本0.9.0新增: GenerativeSelect用于提供特定于SelectCompoundSelect的功能,同时允许SelectBase用于其他类似SELECT的对象,例如TextAsFrom

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

append_group_by T0> ( T1> *条款 T2> ) T3> ¶ T4>

追加应用于此可选项的给定GROUP BY标准。

该标准将被附加到任何预先存在的GROUP BY标准。

这是一种in-place突变方法; group_by()方法是首选,因为它提供了标准的method chaining

append_order_by T0> ( T1> *条款 T2> ) T3> ¶ T4>

附加给定的ORDER BY标准应用于此可选项。

该标准将被附加到任何预先存在的ORDER BY标准。

这是一种in-place突变方法; order_by()方法是首选,因为它提供了标准的method chaining

apply_labels T0> ( T1> ) T2> ¶ T3>

返回一个新的可选项,并将'use_labels'标志设置为True。

这将导致使用标签对其表名称生成列表达式,例如“SELECT somecolumn AS tablename_somecolumn”。这允许包含多个FROM子句的可选项生成一组唯一的列名称,而不考虑各个FROM子句之间的名称冲突。

as_scalar T0> ( T1> ) T2> ¶ T3>
继承自 as_scalar() 方法 SelectBase

返回这个可选项的'标量'表示,它可以用作列表达式。

通常,在其子列中只有一列的select语句可以用作标量表达式。

返回的对象是ScalarSelect的一个实例。

自动提交 T0> ( T1> ) T2> ¶ T3>
继承自 autocommit() 方法 SelectBase

将'autocommit'标志设置为True返回一个新的可选项。

从版本0.6开始弃用: autocommit()已弃用。使用带有'autocommit'标志的Executable.execution_options()

结合 T0> ¶ T1>
继承自 bind 属性 Executable

返回此Executable绑定到的EngineConnection;如果没有找到,则返回None。

这是遍历,在本地进行检查,然后检查关联对象的“from”子句,直到找到绑定的引擎或连接。

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

cte(name=None, recursive=False)
继承自 cte() 方法 HasCTE

返回一个新的CTE或公共表表达式实例。

公用表表达式是一种SQL标准,通过使用一个名为“WITH”的子句,SELECT语句可以使用与主语句一起指定的次要语句。有关UNION的特殊语义也可用于允许“递归”查询,其中SELECT语句可以在先前已选择的一组行上进行绘制。

CTE也可以应用于DML构造对某些数据库的UPDATE,INSERT和DELETE,与RETURNING一起作为CTE行的来源以及CTE行的使用者。

SQLAlchemy将CTE对象检测为与Alias对象类似的对象,作为要传递到语句的FROM子句的特殊元素以及顶部的WITH子句的声明。

在版本1.1中进行了更改:添加了对CTE,CTE添加到UPDATE / INSERT / DELETE的UPDATE / INSERT / DELETE的支持。

参数:
  • name – name given to the common table expression. _FromClause.alias()一样,名称可以保留为None,在这种情况下,查询编译时将使用匿名符号。
  • recursive – if True, will render WITH RECURSIVE. 递归公用表表达式旨在与UNION ALL结合使用,以便从已选择的行中派生行。

以下示例包含两篇来自Postgresql的文档,位于http://www.postgresql.org/docs/current/static/queries-with.html以及其他示例。

例1,非递归:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

例2,与RECURSIVE:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.sub_part,
        parts_alias.c.part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

例3,使用带CTE的UPDATE和INSERT的upsert:

orders = table(
    'orders',
    column('region'),
    column('amount'),
    column('product'),
    column('quantity')
)

upsert = (
    orders.update()
    .where(orders.c.region == 'Region1')
    .values(amount=1.0, product='Product1', quantity=1)
    .returning(*(orders.c._all_columns)).cte('upsert'))

insert = orders.insert().from_select(
    orders.c.keys(),
    select([
        literal('Region1'), literal(1.0),
        literal('Product1'), literal(1)
    ).where(exists(upsert.select()))
)

connection.execute(insert)

也可以看看

orm.query.Query.cte() - HasCTE.cte()的ORM版本。

描述 T0> ¶ T1>

这个FromClause的简要描述。

主要用于错误消息格式。

执行 tt> * multiparams** params T5>
继承自 execute() 方法 Executable

编译并执行Executable

execution_options T0> ( T1> **千瓦 T2> ) T3> ¶ T4>
继承自 execution_options() 方法 tt> Executable

为执行期间生效的语句设置非SQL选项。

执行选项可以在每个语句或每个Connection的基础上设置。此外,Engine和ORM Query对象提供对执行选项的访问,而这些执行选项在连接时进行配置。

execution_options()方法是生成的。返回此语句的新实例,其中包含以下选项:

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

请注意,只有一部分可能的执行选项可以应用于语句 - 这些选项包括“autocommit”和“stream_results”,但不包括“isolation_level”或“c​​ompiled_cache”。有关可能的选项的完整列表,请参阅Connection.execution_options()

FOR_UPDATE T0> ¶ T1>

for_update属性提供传统方言支持。

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

get_children T0> ( T1> ** kwargs T2> ) T3> ¶ T4>
inherited from the get_children() method of ClauseElement

返回这个ClauseElement的直接子元素。

这用于访问遍历。

** kwargs可能包含更改返回的集合的标志,例如为了减少更大的遍历而返回项目的子集,或者从不同的上下文返回子项目(例如模式级集合而不是子句-水平)。

GROUP_BY T0> ( T1> *条款 T2> ) T3> ¶ T4>

返回一个新的可选项,其中应用了GROUP BY标准的给定列表。

该标准将被附加到任何预先存在的GROUP BY标准。

is_derived_from T0> ( T1> fromclause T2> ) T3> ¶ T4>
继承自 is_derived_from() 方法 FromClause

如果FromClause从给定的FromClause中“派生”,则返回True。

一个例子是从表中派生的表的别名。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

标签 T0> ( T1> 名称 T2> ) T3> ¶ T4>
继承自 label() 方法 SelectBase

返回这个可选择的“标量”表示,嵌入为带有标签的子查询。

也可以看看

as_scalar()

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

限制 T0> ( T1> 限制 T2> ) T3> ¶ T4>

返回一个新的可选择的给定LIMIT标准。

这是一个数值,通常在结果选择中呈现为LIMIT表达式。不支持LIMIT的后端将尝试提供类似的功能。

版本1.0.0更改: - Select.limit()现在可以接受任意SQL表达式以及整数值。

参数:limit – an integer LIMIT parameter, or a SQL expression that provides an integer result.
偏移 T0> ( T1> 偏移 T2> ) T3> ¶ T4>

使用给定的OFFSET标准返回一个新的可选项。

This is a numeric value which usually renders as an OFFSET expression in the resulting select. 不支持OFFSET的后端将尝试提供类似的功能。

版本1.0.0更改: - Select.offset()现在可以接受任意SQL表达式以及整数值。

参数:offset – an integer OFFSET parameter, or a SQL expression that provides an integer result.
ORDER_BY T0> ( T1> *条款 T2> ) T3> ¶ T4>

返回一个新的可选项,其中应用了ORDER BY标准的给定列表。

该标准将被附加到任何预先存在的ORDER BY标准。

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

标量 * multiparams** params T5>
inherited from the scalar() method of Executable

编译并执行此Executable,返回结果的标量表示。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

self_group T0> ( T1> 针对=无 T2> ) T3> ¶ T4>
inherited from the self_group() method of ClauseElement

对这个ClauseElement应用“分组”。

子类重写此方法以返回“分组”结构,即括号。In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another select(). (请注意,通常应使用Select.alias()方法创建子查询,因为许多平台需要命名嵌套的SELECT语句)。

由于表达式组合在一起,所以self_group()的应用程序是自动的 - 最终用户代码不需要直接使用此方法。Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

ClauseElement的base self_group()方法仅返回self。

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

with_for_update(nowait=False, read=False, of=None, skip_locked=False, key_share=False)

GenerativeSelect指定一个FOR UPDATE子句。

例如。:

stmt = select([table]).with_for_update(nowait=True)

在像Postgresql或Oracle这样的数据库上,上面的代码会显示如下的语句:

SELECT table.a, table.b FROM table FOR UPDATE NOWAIT

在其他后端,nowait选项被忽略,而是产生:

SELECT table.a, table.b FROM table FOR UPDATE

当不带任何参数调用时,语句将以后缀FOR UPDATE进行呈现。然后可以提供其他参数,这些参数允许使用通用数据库特定的变体。

参数:
  • nowait - boolean;将在Oracle和Postgresql方言中呈现FOR tt> UPDATE NOWAIT
  • - boolean;将在MySQL上呈现LOCK IN SHARE 模式在Postgresql上共享 共享On Postgresql, when combined with nowait, will render FOR SHARE NOWAIT.
  • of – SQL expression or list of SQL expression elements (typically Column objects or a compatible expression) which will render into a FOR UPDATE OF clause; supported by PostgreSQL and Oracle. 可以根据后端呈现为表格或列。
  • skip_locked -

    boolean, will render FOR UPDATE SKIP LOCKED on Oracle and Postgresql dialects or FOR SHARE SKIP LOCKED if read=True is also specified.

    版本1.1.0中的新功能

  • key_share -

    boolean, will render FOR NO KEY UPDATE, or if combined with read=True will render FOR KEY SHARE, on the Postgresql dialect.

    版本1.1.0中的新功能

class sqlalchemy.sql.expression。 HasCTE

Mixin声明一个类包含CTE支持。

版本1.1中的新功能

cte(name=None, recursive=False)

返回一个新的CTE或公共表表达式实例。

公用表表达式是一种SQL标准,通过使用一个名为“WITH”的子句,SELECT语句可以使用与主语句一起指定的次要语句。有关UNION的特殊语义也可用于允许“递归”查询,其中SELECT语句可以在先前已选择的一组行上进行绘制。

CTE也可以应用于DML构造对某些数据库的UPDATE,INSERT和DELETE,与RETURNING一起作为CTE行的来源以及CTE行的使用者。

SQLAlchemy将CTE对象检测为与Alias对象类似的对象,作为要传递到语句的FROM子句的特殊元素以及顶部的WITH子句的声明。

在版本1.1中进行了更改:添加了对CTE,CTE添加到UPDATE / INSERT / DELETE的UPDATE / INSERT / DELETE的支持。

参数:
  • name – name given to the common table expression. _FromClause.alias()一样,名称可以保留为None,在这种情况下,查询编译时将使用匿名符号。
  • recursive – if True, will render WITH RECURSIVE. 递归公用表表达式旨在与UNION ALL结合使用,以便从已选择的行中派生行。

以下示例包含两篇来自Postgresql的文档,位于http://www.postgresql.org/docs/current/static/queries-with.html以及其他示例。

例1,非递归:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

例2,与RECURSIVE:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.sub_part,
        parts_alias.c.part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

例3,使用带CTE的UPDATE和INSERT的upsert:

orders = table(
    'orders',
    column('region'),
    column('amount'),
    column('product'),
    column('quantity')
)

upsert = (
    orders.update()
    .where(orders.c.region == 'Region1')
    .values(amount=1.0, product='Product1', quantity=1)
    .returning(*(orders.c._all_columns)).cte('upsert'))

insert = orders.insert().from_select(
    orders.c.keys(),
    select([
        literal('Region1'), literal(1.0),
        literal('Product1'), literal(1)
    ).where(exists(upsert.select()))
)

connection.execute(insert)

也可以看看

orm.query.Query.cte() - HasCTE.cte()的ORM版本。

class sqlalchemy.sql.expression。 HasPrefixes
prefix_with * expr** kw T5>

在语句关键字后添加一个或多个表达式,即SELECT,INSERT,UPDATE或DELETE。生成。

这用于支持后端特定的前缀关键字,例如由MySQL提供的前缀关键字。

例如。:

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

可以通过多次调用prefix_with()来指定多个前缀。

参数:
  • *expr – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.
  • ** kw - 接受单个关键字'dialect'。这是一个可选的字符串方言名称,它将限制将该前缀的呈现仅限于该方言。
class sqlalchemy.sql.expression。 HasSuffixes
后缀 tt> * expr** kw T5>

在整个语句后添加一个或多个表达式。

这用于在特定结构上支持后端特定的后缀关键字。

例如。:

stmt = select([col1, col2]).cte().suffix_with(
    "cycle empno set y_cycle to 1 default 0", dialect="oracle")

多个后缀可以通过多次调用suffix_with()来指定。

参数:
  • *expr – textual or ClauseElement construct which will be rendered following the target clause.
  • ** kw - 接受单个关键字'dialect'。这是一个可选的字符串方言名称,它将限制仅将该后缀渲染为该方言。
class sqlalchemy.sql.expression.Join(left, right, onclause=None, isouter=False, full=False)

基础:sqlalchemy.sql.expression.FromClause

represent a JOIN construct between two FromClause elements.

The public constructor function for Join is the module-level join() function, as well as the FromClause.join() method of any FromClause (e.g. such as Table).

__init__(left, right, onclause=None, isouter=False, full=False)

构建一个新的Join

这里通常的入口点是任何FromClause对象的join()函数或FromClause.join()方法。

alias(name=None, flat=False)

返回此Join的别名。

这里的默认行为是首先从Join生成一个SELECT构造,然后从中产生一个Alias所以给了一个形式的加入:

j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)

本身的JOIN看起来像:

table_a JOIN table_b ON table_a.id = table_b.a_id

Whereas the alias of the above, j.alias(), would in a SELECT context look like:

(SELECT table_a.id AS table_a_id, table_b.id AS table_b_id,
    table_b.a_id AS table_b_a_id
    FROM table_a
    JOIN table_b ON table_a.id = table_b.a_id) AS anon_1

给定一个Join对象j,等价的长手形式是:

from sqlalchemy import select, alias
j = alias(
    select([j.left, j.right]).\
        select_from(j).\
        with_labels(True).\
        correlate(False),
    name=name
)

Join.alias()生成的可选择列与以单个名称显示的两个单独可选列的列相同 - 各列为“自动标记”,即.c.所得到的Alias的集合使用<tablename>_<columname>方案表示各个列的名称:

j.c.table_a_id
j.c.table_b_a_id

Join.alias()还具有替代选项,用于别名联接,不会产生封闭的SELECT,并且通常不会将标签应用于列名称。flat=True选项将分别针对左侧和右侧调用FromClause.alias()使用这个选项,不会产生新的SELECT;我们相反,从一个构造如下:

j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
j = j.alias(flat=True)

我们得到如下结果:

table_a AS table_a_1 JOIN table_b AS table_b_1 ON
table_a_1.id = table_b_1.a_id

flat=True参数也会传播到包含的selectables,以便组合连接如:

j = table_a.join(
        table_b.join(table_c,
                table_b.c.id == table_c.c.b_id),
        table_b.c.a_id == table_a.c.id
    ).alias(flat=True)

会产生如下表达式:

table_a AS table_a_1 JOIN (
        table_b AS table_b_1 JOIN table_c AS table_c_1
        ON table_b_1.id = table_c_1.b_id
) ON table_a_1.id = table_b_1.a_id

独立的alias()函数以及基础的FromClause.alias()方法也支持flat=True参数作为无操作,以便参数可以传递给任何可选择的alias()方法。

版本0.9.0新增:增加了flat=True选项来创建连接的“别名”,而不用在SELECT子查询内部进行封闭。

参数:
  • 名称 - 给予别名的名称。
  • flat -

    如果为True,则生成此Join的左侧和右侧的别名,并返回这两个可选项的联接。这会生成不包含封闭SELECT的连接表达式。

    版本0.9.0中的新功能

也可以看看

alias()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

选择 whereclause = None** kwargs / T5>

Join中创建一个Select

给定一个Join对象j,等价的长手形式是:

from sqlalchemy import select
j = select([j.left, j.right], **kw).\
            where(whereclause).\
            select_from(j)
参数:
  • whereclause – the WHERE criterion that will be sent to the select() function
  • **kwargs – all other kwargs are sent to the underlying select() function.
tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

class sqlalchemy.sql.expression.Lateral(selectable, name=None)

基础:sqlalchemy.sql.expression.Alias

表示一个LATERAL子查询。

This object is constructed from the lateral() module level function as well as the FromClause.lateral() method available on all FromClause subclasses.

尽管LATERAL是SQL标准的一部分,但只有更新的Postgresql版本才支持此关键字。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

class sqlalchemy.sql.expression.ScalarSelect(element)

基础:sqlalchemy.sql.expression.Generativesqlalchemy.sql.expression.Grouping

其中 T0> ( T1> 暴 T2> ) T3> ¶ T4>

对此ScalarSelect引用的SELECT语句应用WHERE子句。

class sqlalchemy.sql.expression。 选择 columns =无 whereclause = Nonefrom_obj = Nonedistinct = False具有=无correlate = t9>,前缀=无后缀=无** kwargs >

基础:sqlalchemy.sql.expression.HasPrefixessqlalchemy.sql.expression.HasSuffixessqlalchemy.sql.expression.GenerativeSelect

代表一个SELECT语句。

__init__(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)

构建一个新的Select对象。

这个构造函数被镜像为公共API函数;有关完整的用法和参数说明,请参阅select()

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

append_column T0> ( T1> 列 T2> ) T3> ¶ T4>

将给定的列表达式追加到此select()构造的columns子句中。

这是一种in-place突变方法; column()方法是首选,因为它提供了标准的method chaining

append_correlation T0> ( T1> fromclause T2> ) T3> ¶ T4>

将给定的相关表达式附加到这个select()结构中。

这是一种in-place突变方法; correlate()方法是首选,因为它提供了标准的method chaining

append_from T0> ( T1> fromclause T2> ) T3> ¶ T4>

将给定的FromClause表达式附加到这个select()构造的FROM子句中。

这是一种in-place突变方法; select_from()方法是首选,因为它提供了标准的method chaining

append_group_by T0> ( T1> *条款 T2> ) T3> ¶ T4>

追加应用于此可选项的给定GROUP BY标准。

该标准将被附加到任何预先存在的GROUP BY标准。

这是一种in-place突变方法; group_by()方法是首选,因为它提供了标准的method chaining

append_having T0> ( T1> 具有 T2> ) T3> ¶ T4>

将给定的表达式追加到这个select()构造的HAVING标准中。

该表达式将通过AND连接到现有的HAVING标准。

This is an in-place mutation method; the having() method is preferred, as it provides standard method chaining.

append_order_by T0> ( T1> *条款 T2> ) T3> ¶ T4>

附加给定的ORDER BY标准应用于此可选项。

该标准将被附加到任何预先存在的ORDER BY标准。

这是一种in-place突变方法; order_by()方法是首选,因为它提供了标准的method chaining

append_prefix T0> ( T1> 子句 T2> ) T3> ¶ T4>

将给定的列子句前缀表达式附加到此select()构造。

这是一种in-place突变方法; prefix_with()方法是首选,因为它提供了标准的method chaining

append_whereclause T0> ( T1> whereclause T2> ) T3> ¶ T4>

将给定的表达式追加到这个select()构造的WHERE标准中。

该表达式将通过AND连接到现有的WHERE标准。

这是一种in-place突变方法; where()方法是首选,因为它提供标准的method chaining

apply_labels T0> ( T1> ) T2> ¶ T3>

返回一个新的可选项,并将'use_labels'标志设置为True。

这将导致使用标签对其表名称生成列表达式,例如“SELECT somecolumn AS tablename_somecolumn”。这允许包含多个FROM子句的可选项生成一组唯一的列名称,而不考虑各个FROM子句之间的名称冲突。

as_scalar T0> ( T1> ) T2> ¶ T3>
继承自 as_scalar() 方法 SelectBase

返回这个可选项的'标量'表示,它可以用作列表达式。

通常,在其子列中只有一列的select语句可以用作标量表达式。

返回的对象是ScalarSelect的一个实例。

自动提交 T0> ( T1> ) T2> ¶ T3>
继承自 autocommit() 方法 SelectBase

将'autocommit'标志设置为True返回一个新的可选项。

从版本0.6开始弃用: autocommit()已弃用。使用带有'autocommit'标志的Executable.execution_options()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ( T1> 列 T2> ) T3> ¶ T4>

返回一个新的select()构造,并将给定的列表达式添加到它的columns子句中。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

归属关系 T0> ( T1> * fromclauses T2> ) T3> ¶ T4>

返回一个新的Select,它将给定的FROM子句与一个包含Select的FROM子句关联起来。

调用此方法会关闭Select对象的“自动关联”的默认行为。通常,出现在Select中的FROM元素将通过它的WHERE clause,ORDER BY,HAVING或columns clause这个Select对象的FROM clause使用Select.correlate()方法设置显式相关集合,可以提供一个固定的FROM对象列表,这些对象可能会在此过程中发生。

当使用Select.correlate()应用特定的FROM子句进行关联时,无论此Select对象相对于将Select这与“自动关联”的行为形成鲜明对比,该行为仅与立即包含Select相关。多级关联确保封闭和封闭Select之间的链接始终通过至少一个WHERE / ORDER BY / HAVING / columns子句进行关联。

如果传递None,则Select对象不会关联任何FROM条目,并且所有对象都将无条件地呈现在本地FROM子句中。

参数: * fromclauses -

a list of one or more FromClause constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate collection.

在版本0.8.0中更改: ORM映射类被Select.correlate()接受。

版本0.8.0中已更改: Select.correlate()方法不再无条件地从FROM子句中删除条目;相反,候选FROM条目还必须与位于封闭Select中的FROM条目匹配,该条目最终包含在WHERE子句,ORDER BY子句,HAVING子句或columns子句中一个封闭的Select()

在版本0.8.2中更改:显式关联通过Select对象的任何级别嵌套进行;在以前的0.8版本中,相关只会发生在相对于立即封闭的Select结构中。

correlate_except T0> ( T1> * fromclauses T2> ) T3> ¶ T4>

返回一个新的Select,它将从自动关联过程中省略给定的FROM子句。

调用Select.correlate_except()会关闭给定FROM元素的Select对象的“自动关联”默认行为。此处指定的元素将无条件出现在FROM列表中,而所有其他FROM元素仍保持正常的自动关联行为。

在0.8.2版本中进行了更改:Select.correlate_except()方法进行了改进,以完全防止此处指定的FROM子句从此Select

如果传递None,则Select对象将关联其所有FROM条目。

版本0.8.2更改:调用correlate_except(None)将正确地自动关联所有FROM子句。

参数:*fromclauses – a list of one or more FromClause constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection.
对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

cte(name=None, recursive=False)
继承自 cte() 方法 HasCTE

返回一个新的CTE或公共表表达式实例。

公用表表达式是一种SQL标准,通过使用一个名为“WITH”的子句,SELECT语句可以使用与主语句一起指定的次要语句。有关UNION的特殊语义也可用于允许“递归”查询,其中SELECT语句可以在先前已选择的一组行上进行绘制。

CTE也可以应用于DML构造对某些数据库的UPDATE,INSERT和DELETE,与RETURNING一起作为CTE行的来源以及CTE行的使用者。

SQLAlchemy将CTE对象检测为与Alias对象类似的对象,作为要传递到语句的FROM子句的特殊元素以及顶部的WITH子句的声明。

在版本1.1中进行了更改:添加了对CTE,CTE添加到UPDATE / INSERT / DELETE的UPDATE / INSERT / DELETE的支持。

参数:
  • name – name given to the common table expression. _FromClause.alias()一样,名称可以保留为None,在这种情况下,查询编译时将使用匿名符号。
  • recursive – if True, will render WITH RECURSIVE. 递归公用表表达式旨在与UNION ALL结合使用,以便从已选择的行中派生行。

以下示例包含两篇来自Postgresql的文档,位于http://www.postgresql.org/docs/current/static/queries-with.html以及其他示例。

例1,非递归:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

例2,与RECURSIVE:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.sub_part,
        parts_alias.c.part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

例3,使用带CTE的UPDATE和INSERT的upsert:

orders = table(
    'orders',
    column('region'),
    column('amount'),
    column('product'),
    column('quantity')
)

upsert = (
    orders.update()
    .where(orders.c.region == 'Region1')
    .values(amount=1.0, product='Product1', quantity=1)
    .returning(*(orders.c._all_columns)).cte('upsert'))

insert = orders.insert().from_select(
    orders.c.keys(),
    select([
        literal('Region1'), literal(1.0),
        literal('Product1'), literal(1)
    ).where(exists(upsert.select()))
)

connection.execute(insert)

也可以看看

orm.query.Query.cte() - HasCTE.cte()的ORM版本。

描述 T0> ¶ T1>

这个FromClause的简要描述。

主要用于错误消息格式。

不同 T0> ( T1> * EXPR T2> ) T3> ¶ T4>

返回一个新的select()构造,它将DISTINCT应用到它的columns子句。

参数: * expr - 可选的列表达式。当存在时,Postgresql方言将呈现DISTINCT ON (&lt;表达式&gt;)结构。
except_(other, **kwargs)

针对给定的selectable返回此select()构造的SQL EXCEPT。

except_all 其他** kwargs t5 >

根据给定的selectable返回SQL EXCEPT ALL的所有select()构造。

执行 tt> * multiparams** params T5>
继承自 execute() 方法 Executable

编译并执行Executable

execution_options T0> ( T1> **千瓦 T2> ) T3> ¶ T4>
继承自 execution_options() 方法 tt> Executable

为执行期间生效的语句设置非SQL选项。

执行选项可以在每个语句或每个Connection的基础上设置。此外,Engine和ORM Query对象提供对执行选项的访问,而这些执行选项在连接时进行配置。

execution_options()方法是生成的。返回此语句的新实例,其中包含以下选项:

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

请注意,只有一部分可能的执行选项可以应用于语句 - 这些选项包括“autocommit”和“stream_results”,但不包括“isolation_level”或“c​​ompiled_cache”。有关可能的选项的完整列表,请参阅Connection.execution_options()

FOR_UPDATE T0> ¶ T1>
继承自 for_update 属性 GenerativeSelect

for_update属性提供传统方言支持。

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

320交织 T0> ¶ T1>

返回FromClause元素的显示列表。

get_children column_collections = True** kwargs / T5>

按照ClauseElement规范返回子元素。

GROUP_BY T0> ( T1> *条款 T2> ) T3> ¶ T4>
group_by() 方法继承的GenerativeSelect

返回一个新的可选项,其中应用了GROUP BY标准的给定列表。

该标准将被附加到任何预先存在的GROUP BY标准。

具有 T0> ( T1> 具有 T2> ) T3> ¶ T4>

返回一个新的select()构造,将给定的表达式添加到它的HAVING子句中,通过AND连接到现有子句(如果有的话)。

inner_columns T0> ¶ T1>

所有ColumnElement表达式的迭代器,这些表达式将被渲染到结果SELECT语句的columns子句中。

相交 T0> ( T1> 其他 T2>, ** kwargs T3> ) T4> ¶ T5 >

根据给定的selectable返回此select()构造的SQL INTERSECT。

intersect_all 其他** kwargs t5 >

根据给定的selectable返回一个SQL INTERSECT ALL这个select()构造。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

标签 T0> ( T1> 名称 T2> ) T3> ¶ T4>
继承自 label() 方法 SelectBase

返回这个可选择的“标量”表示,嵌入为带有标签的子查询。

也可以看看

as_scalar()

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

限制 T0> ( T1> 限制 T2> ) T3> ¶ T4>
inherited from the limit() method of GenerativeSelect

返回一个新的可选择的给定LIMIT标准。

这是一个数值,通常在结果选择中呈现为LIMIT表达式。不支持LIMIT的后端将尝试提供类似的功能。

版本1.0.0更改: - Select.limit()现在可以接受任意SQL表达式以及整数值。

参数:limit – an integer LIMIT parameter, or a SQL expression that provides an integer result.
locate_all_froms(*args, **kw)

返回此Select所引用的所有FromClause元素的集合。

这个集合是由froms属性返回的超集,这个属性专门用于那些实际将被渲染的FromClause元素。

偏移 T0> ( T1> 偏移 T2> ) T3> ¶ T4>
inherited from the offset() method of GenerativeSelect

使用给定的OFFSET标准返回一个新的可选项。

This is a numeric value which usually renders as an OFFSET expression in the resulting select. 不支持OFFSET的后端将尝试提供类似的功能。

版本1.0.0更改: - Select.offset()现在可以接受任意SQL表达式以及整数值。

参数:offset – an integer OFFSET parameter, or a SQL expression that provides an integer result.
ORDER_BY T0> ( T1> *条款 T2> ) T3> ¶ T4>
inherited from the order_by() method of GenerativeSelect

返回一个新的可选项,其中应用了ORDER BY标准的给定列表。

该标准将被附加到任何预先存在的ORDER BY标准。

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
prefix_with * expr** kw T5>
继承自 prefix_with() 方法 HasPrefixes

在语句关键字后添加一个或多个表达式,即SELECT,INSERT,UPDATE或DELETE。生成。

这用于支持后端特定的前缀关键字,例如由MySQL提供的前缀关键字。

例如。:

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

可以通过多次调用prefix_with()来指定多个前缀。

参数:
  • *expr – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.
  • ** kw - 接受单个关键字'dialect'。这是一个可选的字符串方言名称,它将限制将该前缀的呈现仅限于该方言。
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

reduce_columns T0> ( T1> only_synonyms =真 T2> ) T3> ¶ T4>

返回一个新的:func`.select`构造,其中包含从列子句中删除的冗余命名的等价值列。

这里的“冗余”表示两列中的一列是基于外键引用另一列,或者通过语句的WHERE子句中的简单相等比较来引用。The primary purpose of this method is to automatically construct a select statement with all uniquely-named columns, without the need to use table-qualified labels as apply_labels() does.

当根据外键省略列时,被引用的列是保留的列。当基于WHERE eqivalence省略列时,columns子句中的第一列是保留的列。

参数:only_synonyms – when True, limit the removal of columns to those which have the same name as the equivalent. 否则,将删除所有与另一个等效的列。

0.8版本中的新功能

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

标量 * multiparams** params T5>
inherited from the scalar() method of Executable

编译并执行此Executable,返回结果的标量表示。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

select_from T0> ( T1> fromclause T2> ) T3> ¶ T4>

返回一个新的select()结构,并将给定的FROM表达式合并到它的FROM对象列表中。

例如。:

table1 = table('t1', column('a'))
table2 = table('t2', column('b'))
s = select([table1.c.a]).\
    select_from(
        table1.join(table2, table1.c.a==table2.c.b)
    )

“from”列表是每个元素身份的唯一集合,因此添加一个已经存在的Table或其他可选项将不起作用。传递引用已存在的Table或其他可选项的Join将会在呈现的FROM列表中隐藏作为单个元素可选择的存在,而不是呈现它变成一个JOIN子句。

尽管Select.select_from()的典型用途是用连接替换默认的派生FROM子句,但如果需要,也可以使用单个表元素多次调用它,如果需要的话FROM子句不能从columns子句中完全派生:

select([func.count('*')]).select_from(table1)
self_group T0> ( T1> 针对=无 T2> ) T3> ¶ T4>

按照ClauseElement规范返回“分组”结构。

这产生了一个可以嵌入到表达式中的元素。请注意,在构建表达式时,会根据需要自动调用此方法,并且不需要明确使用。

后缀 tt> * expr** kw T5>
inherited from the suffix_with() method of HasSuffixes

在整个语句后添加一个或多个表达式。

这用于在特定结构上支持后端特定的后缀关键字。

例如。:

stmt = select([col1, col2]).cte().suffix_with(
    "cycle empno set y_cycle to 1 default 0", dialect="oracle")

多个后缀可以通过多次调用suffix_with()来指定。

参数:
  • *expr – textual or ClauseElement construct which will be rendered following the target clause.
  • ** kw - 接受单个关键字'dialect'。这是一个可选的字符串方言名称,它将限制仅将该后缀渲染为该方言。
tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

union 其他** kwargs t5 >

根据给定的selectable返回此select()构造的SQL UNION。

union_all 其他** kwargs t5 >

针对给定的selectable返回此select()构造的SQL UNION ALL。

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

其中 T0> ( T1> whereclause T2> ) T3> ¶ T4>

返回一个新的select()构造,将给定的表达式添加到其WHERE子句中,通过AND连接到现有子句(如果有的话)。

with_for_update(nowait=False, read=False, of=None, skip_locked=False, key_share=False)
inherited from the with_for_update() method of GenerativeSelect

GenerativeSelect指定一个FOR UPDATE子句。

例如。:

stmt = select([table]).with_for_update(nowait=True)

在像Postgresql或Oracle这样的数据库上,上面的代码会显示如下的语句:

SELECT table.a, table.b FROM table FOR UPDATE NOWAIT

在其他后端,nowait选项被忽略,而是产生:

SELECT table.a, table.b FROM table FOR UPDATE

当不带任何参数调用时,语句将以后缀FOR UPDATE进行呈现。然后可以提供其他参数,这些参数允许使用通用数据库特定的变体。

参数:
  • nowait - boolean;将在Oracle和Postgresql方言中呈现FOR tt> UPDATE NOWAIT
  • - boolean;将在MySQL上呈现LOCK IN SHARE 模式在Postgresql上共享 共享On Postgresql, when combined with nowait, will render FOR SHARE NOWAIT.
  • of – SQL expression or list of SQL expression elements (typically Column objects or a compatible expression) which will render into a FOR UPDATE OF clause; supported by PostgreSQL and Oracle. 可以根据后端呈现为表格或列。
  • skip_locked -

    boolean, will render FOR UPDATE SKIP LOCKED on Oracle and Postgresql dialects or FOR SHARE SKIP LOCKED if read=True is also specified.

    版本1.1.0中的新功能

  • key_share -

    boolean, will render FOR NO KEY UPDATE, or if combined with read=True will render FOR KEY SHARE, on the Postgresql dialect.

    版本1.1.0中的新功能

with_hint(selectable, text, dialect_name='*')

给这个Select添加一个索引或其他执行上下文提示。

相对于给定的TableAlias作为selectable传递,提示文本呈现在正在使用的数据库后端的适当位置。论据。方言实现通常使用Python字符串替换语法和令牌%(name)s来呈现表或别名的名称。例如。在使用Oracle时,需要:

select([mytable]).\
    with_hint(mytable, "index(%(name)s ix_mytable)")

将SQL呈现为:

select /*+ index(mytable ix_mytable) */ ... from mytable

The dialect_name option will limit the rendering of a particular hint to a particular backend. 例如,同时为Oracle和Sybase添加提示:

select([mytable]).\
    with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\
    with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
with_only_columns T0> ( T1> 列 T2> ) T3> ¶ T4>

返回一个新的select()结构,其中的columns子句替换为给定的列。

版本0.7.3更改:由于错误修复,此方法在版本0.7.3中有轻微的行为改变。在版本0.7.3之前,已经预先计算了select()的FROM子句,并添加了新列;在0.7.3及更高版本中,它是在编译时计算的,解决了将列与父表后期绑定的问题。这改变了Select.with_only_columns()的行为,因为删除了不再在新列表中表示的FROM子句,但是这种行为更一致,因为FROM子句始终从当前列子句派生。这种方法的最初意图是允许修剪现有列列表的列数比原来存在的列数少;在完全不同的列表中替换列表的用例在0.7.3发布之前一直没有预料到;下面的使用指南说明了这应该如何完成。

这个方法与使用给定的columns子句调用原始的select()完全等价。即一份声明:

s = select([table1.c.a, table1.c.b])
s = s.with_only_columns([table1.c.b])

应该完全等同于:

s = select([table1.c.b])

这意味着只有从列列表派生的FROM子句将被丢弃,如果新列列表不再包含该FROM:

>>> table1 = table('t1', column('a'), column('b'))
>>> table2 = table('t2', column('a'), column('b'))
>>> s1 = select([table1.c.a, table2.c.b])
>>> print s1
SELECT t1.a, t2.b FROM t1, t2
>>> s2 = s1.with_only_columns([table2.c.b])
>>> print s2
SELECT t2.b FROM t1

在构造中维护特定FROM子句的首选方法,假设它不会在其他地方表示(即不在WHERE子句中等)是使用Select.select_from()来设置它:

>>> s1 = select([table1.c.a, table2.c.b]).\
...         select_from(table1.join(table2,
...                 table1.c.a==table2.c.a))
>>> s2 = s1.with_only_columns([table2.c.b])
>>> print s2
SELECT t2.b FROM t1 JOIN t2 ON t1.a=t2.a

还应注意使用传递给Select.with_only_columns()的正确的一组列对象。由于该方法基本上等效于首先用给定列调用select()构造,传递给Select.with_only_columns()的列通常应该是一个子集传递给select()构造的那些,而不是那些可从select().c集合中获得的构造。那是:

s = select([table1.c.a, table1.c.b]).select_from(table1)
s = s.with_only_columns([table1.c.b])

不是

# usually incorrect
s = s.with_only_columns([s.c.b])

后者将生成SQL:

SELECT b
FROM (SELECT t1.a AS a, t1.b AS b
FROM t1), t1

由于select()构造基本上被要求从table1以及其自身中选择。

with_statement_hint(text, dialect_name='*')

向此Select添加语句提示。

该方法类似于Select.with_hint(),不同之处在于它不需要单独的表格,而是作为整体应用于该语句。

此处的提示仅针对后端数据库,并可能包含隔离级别,文件指令,提取指令等指令。

版本1.0.0中的新功能

也可以看看

Select.with_hint()

class sqlalchemy.sql.expression。 可选

基础:sqlalchemy.sql.expression.ClauseElement

将课程标记为可选

class sqlalchemy.sql.expression。 SelectBase

基础:sqlalchemy.sql.expression.HasCTEsqlalchemy.sql.expression.Executablesqlalchemy.sql.expression.FromClause

SELECT语句的基类。

这包括SelectCompoundSelectTextAsFrom

as_scalar T0> ( T1> ) T2> ¶ T3>

返回这个可选项的'标量'表示,它可以用作列表达式。

通常,在其子列中只有一列的select语句可以用作标量表达式。

返回的对象是ScalarSelect的一个实例。

自动提交 T0> ( T1> ) T2> ¶ T3>

将'autocommit'标志设置为True返回一个新的可选项。

从版本0.6开始弃用: autocommit()已弃用。使用带有'autocommit'标志的Executable.execution_options()

标签 T0> ( T1> 名称 T2> ) T3> ¶ T4>

返回这个可选择的“标量”表示,嵌入为带有标签的子查询。

也可以看看

as_scalar()

class sqlalchemy.sql.expression。 TableClause name*列 T5> ) T6> ¶ T7>

基础:sqlalchemy.sql.expression.Immutablesqlalchemy.sql.expression.FromClause

代表最小的“表”结构。

这是一个轻量级的表格对象,它只有一个名称和一个列集合,通常由expression.column()函数生成:

from sqlalchemy import table, column

user = table("user",
        column("id"),
        column("name"),
        column("description"),
)

TableClause结构可作为更常用的Table对象的基础,提供常见的FromClause服务集合,包括.c.收集和声明生成方法。

It does not provide all the additional schema-level services of Table, including constraints, references to other tables, or support for MetaData-level services. 当一个更完全的Table不在手边时,它可以作为一个临时构造用于生成快速SQL语句。

__ init __ name*列

构建一个新的TableClause对象。

这个构造函数被镜像为公共API函数;有关完整的用法和参数说明,请参阅table()

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

删除 whereclause = None** kwargs / T5>

根据这个TableClause生成一个delete()结构。

例如。:

table.delete().where(table.c.id==7)

有关参数和使用信息,请参阅delete()

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

implicit_returning = False

TableClause doesn’t support having a primary key or column -level defaults, so implicit returning doesn’t apply.

insert values = Noneinline = False** kwargs ) T5> ¶ T6>

针对这个TableClause生成一个insert()结构。

例如。:

table.insert().values(name='foo')

有关参数和使用信息,请参见insert()

is_derived_from T0> ( T1> fromclause T2> ) T3> ¶ T4>
继承自 is_derived_from() 方法 FromClause

如果FromClause从给定的FromClause中“派生”,则返回True。

一个例子是从表中派生的表的别名。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

self_group T0> ( T1> 针对=无 T2> ) T3> ¶ T4>
inherited from the self_group() method of ClauseElement

对这个ClauseElement应用“分组”。

子类重写此方法以返回“分组”结构,即括号。In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another select(). (请注意,通常应使用Select.alias()方法创建子查询,因为许多平台需要命名嵌套的SELECT语句)。

由于表达式组合在一起,所以self_group()的应用程序是自动的 - 最终用户代码不需要直接使用此方法。Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

ClauseElement的base self_group()方法仅返回self。

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

update(whereclause=None, values=None, inline=False, **kwargs)

根据这个TableClause生成一个update()结构。

例如。:

table.update().where(table.c.id==7).values(name='foo')

有关参数和使用信息,请参阅update()

class sqlalchemy.sql.expression.TableSample(selectable, sampling, name=None, seed=None)

基础:sqlalchemy.sql.expression.Alias

表示一个TABLESAMPLE子句。

该对象由所有FromClause子类上的tablesample()模块级函数以及FromClause.tablesample()方法构造而成。

版本1.1中的新功能

也可以看看

tablesample()

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。

class sqlalchemy.sql.expression。 TextAsFrom textcolumns positions = False

基础:sqlalchemy.sql.expression.SelectBase

SelectBase界面中包装TextClause结构。

This allows the TextClause object to gain a .c collection and other FROM-like capabilities such as FromClause.alias(), SelectBase.cte(), etc.

TextAsFrom结构是通过TextClause.columns()方法生成的 - 请参阅该方法以获取详细信息。

版本0.9.0中的新功能

alias(name=None, flat=False)
alias() 方法继承 FromClause

返回FromClause的别名。

这是调用的简写:

from sqlalchemy import alias
a = alias(self, name=name)

有关详细信息,请参阅alias()

as_scalar T0> ( T1> ) T2> ¶ T3>
继承自 as_scalar() 方法 SelectBase

返回这个可选项的'标量'表示,它可以用作列表达式。

通常,在其子列中只有一列的select语句可以用作标量表达式。

返回的对象是ScalarSelect的一个实例。

自动提交 T0> ( T1> ) T2> ¶ T3>
继承自 autocommit() 方法 SelectBase

将'autocommit'标志设置为True返回一个新的可选项。

从版本0.6开始弃用: autocommit()已弃用。使用带有'autocommit'标志的Executable.execution_options()

结合 T0> ¶ T1>
继承自 bind 属性 Executable

返回此Executable绑定到的EngineConnection;如果没有找到,则返回None。

这是遍历,在本地进行检查,然后检查关联对象的“from”子句,直到找到绑定的引擎或连接。

C T0> ¶ T1>
inherited from the c attribute of FromClause

columns属性的别名。

列 T0> ¶ T1>
inherited from the columns attribute of FromClause

FromClause维护的ColumnElement对象的基于命名的集合。

columnsc集合是使用表绑定或其他可选绑定列构建SQL表达式的入口:

select([mytable]).where(mytable.c.somecolumn == 5)
比较 其他** kw t5 >
inherited from the compare() method of ClauseElement

将此ClauseElement与给定的ClauseElement进行比较。

子类应该覆盖默认行为,这是一种直接的身份比较。

** kw是由subclass compare()方法消耗的参数,可用于修改比较条件。(请参阅ColumnElement

编译 bind = Nonedialect = None** kw ) T5> ¶ T6>
inherited from the compile() method of ClauseElement

编译这个SQL表达式。

返回值是一个Compiled对象。对返回值调用str()unicode()将产生结果的字符串表示形式。Compiled对象还可以使用params访问器返回一个绑定参数名称和值的字典。

参数:
  • bind – An Engine or Connection from which a Compiled will be acquired. 这个参数优先于这个ClauseElement的绑定引擎,如果有的话。
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. 如果None,则呈现目标表格对象中的所有列。
  • dialect – A Dialect instance from which a Compiled will be acquired. 该参数优先于bind参数以及ClauseElement的绑定引擎(如果有的话)。
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. 这通常是指序列执行,但也可能指与主键Column关联的任何服务器端默认生成函数。
  • compile_kwargs -

    在所有“访问”方法中将传递给编译器的附加参数的可选字典。例如,这允许将自定义标志传递给自定义编译构造。它也用于传递literal_binds标志的情况:

    from sqlalchemy.sql import table, column, select
    
    t = table('t', column('x'))
    
    s = select([t]).where(t.c.x == 5)
    
    print s.compile(compile_kwargs={"literal_binds": True})

    版本0.9.0中的新功能

对等元等于 等值
inherited from the correspond_on_equivalents() method of FromClause

返回给定列的相应列,或者如果None搜索给定字典中的匹配项。

对应列 require_embedded = False t5 >

给定一个ColumnElement,从这个Selectable对象的原始Column通过共同的祖先返回导出的ColumnElement柱。

参数:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
count whereclause = None** params / T5>
继承自 count() 方法 FromClause

返回一个根据FromClause生成的SELECT COUNT。

从版本1.1开始弃用: FromClause.count()已弃用。对行进行计数需要正确的列表达式和联接,DISTINCT等。必须提出,否则结果可能不是预期的结果。请直接使用适当的func.count()表达式。

该函数针对表的主键中的第一列或整个表中的第一列生成COUNT。显式使用func.count()应该是首选的:

row_count = conn.scalar(
    select([func.count('*')]).select_from(table)
)

也可以看看

func

cte(name=None, recursive=False)
继承自 cte() 方法 HasCTE

返回一个新的CTE或公共表表达式实例。

公用表表达式是一种SQL标准,通过使用一个名为“WITH”的子句,SELECT语句可以使用与主语句一起指定的次要语句。有关UNION的特殊语义也可用于允许“递归”查询,其中SELECT语句可以在先前已选择的一组行上进行绘制。

CTE也可以应用于DML构造对某些数据库的UPDATE,INSERT和DELETE,与RETURNING一起作为CTE行的来源以及CTE行的使用者。

SQLAlchemy将CTE对象检测为与Alias对象类似的对象,作为要传递到语句的FROM子句的特殊元素以及顶部的WITH子句的声明。

在版本1.1中进行了更改:添加了对CTE,CTE添加到UPDATE / INSERT / DELETE的UPDATE / INSERT / DELETE的支持。

参数:
  • name – name given to the common table expression. _FromClause.alias()一样,名称可以保留为None,在这种情况下,查询编译时将使用匿名符号。
  • recursive – if True, will render WITH RECURSIVE. 递归公用表表达式旨在与UNION ALL结合使用,以便从已选择的行中派生行。

以下示例包含两篇来自Postgresql的文档,位于http://www.postgresql.org/docs/current/static/queries-with.html以及其他示例。

例1,非递归:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

例2,与RECURSIVE:

from sqlalchemy import (Table, Column, String, Integer,
                        MetaData, select, func)

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.sub_part,
        parts_alias.c.part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

例3,使用带CTE的UPDATE和INSERT的upsert:

orders = table(
    'orders',
    column('region'),
    column('amount'),
    column('product'),
    column('quantity')
)

upsert = (
    orders.update()
    .where(orders.c.region == 'Region1')
    .values(amount=1.0, product='Product1', quantity=1)
    .returning(*(orders.c._all_columns)).cte('upsert'))

insert = orders.insert().from_select(
    orders.c.keys(),
    select([
        literal('Region1'), literal(1.0),
        literal('Product1'), literal(1)
    ).where(exists(upsert.select()))
)

connection.execute(insert)

也可以看看

orm.query.Query.cte() - HasCTE.cte()的ORM版本。

描述 T0> ¶ T1>

这个FromClause的简要描述。

主要用于错误消息格式。

执行 tt> * multiparams** params T5>
继承自 execute() 方法 Executable

编译并执行Executable

execution_options T0> ( T1> **千瓦 T2> ) T3> ¶ T4>
继承自 execution_options() 方法 tt> Executable

为执行期间生效的语句设置非SQL选项。

执行选项可以在每个语句或每个Connection的基础上设置。此外,Engine和ORM Query对象提供对执行选项的访问,而这些执行选项在连接时进行配置。

execution_options()方法是生成的。返回此语句的新实例,其中包含以下选项:

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

请注意,只有一部分可能的执行选项可以应用于语句 - 这些选项包括“autocommit”和“stream_results”,但不包括“isolation_level”或“c​​ompiled_cache”。有关可能的选项的完整列表,请参阅Connection.execution_options()

foreign_keys T0> ¶ T1>
继承自 foreign_keys 属性 FromClause

返回FromClause引用的ForeignKey对象的集合。

get_children T0> ( T1> ** kwargs T2> ) T3> ¶ T4>
inherited from the get_children() method of ClauseElement

返回这个ClauseElement的直接子元素。

这用于访问遍历。

** kwargs可能包含更改返回的集合的标志,例如为了减少更大的遍历而返回项目的子集,或者从不同的上下文返回子项目(例如模式级集合而不是子句-水平)。

is_derived_from T0> ( T1> fromclause T2> ) T3> ¶ T4>
继承自 is_derived_from() 方法 FromClause

如果FromClause从给定的FromClause中“派生”,则返回True。

一个例子是从表中派生的表的别名。

join(right, onclause=None, isouter=False, full=False)
inherited from the join() method of FromClause

FromClause返回Join到另一个FromClause

例如。:

from sqlalchemy import join

j = user_table.join(address_table,
                user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)

会沿着以下几行发出SQL:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。意味着FromClause.join.isouter

    版本1.1中的新功能

也可以看看

join() - 独立功能

Join - 生成的对象的类型

标签 T0> ( T1> 名称 T2> ) T3> ¶ T4>
继承自 label() 方法 SelectBase

返回这个可选择的“标量”表示,嵌入为带有标签的子查询。

也可以看看

as_scalar()

横向 T0> ( T1> 名=无 T2> ) T3> ¶ T4>
lateral() 方法继承 FromClause

返回这个FromClause的LATERAL别名。

返回值是由顶层lateral()函数提供的Lateral结构。

版本1.1中的新功能

也可以看看

LATERAL correlation - overview of usage.

外连接 onclause =无full = False ) T5> ¶ T6>
outerjoin() 方法继承 FromClause

Return a Join from this FromClause to another FromClause, with the “isouter” flag set to True.

例如。:

from sqlalchemy import outerjoin

j = user_table.outerjoin(address_table,
                user_table.c.id == address_table.c.user_id)

以上相当于:

j = user_table.join(
    address_table,
    user_table.c.id == address_table.c.user_id,
    isouter=True)
参数:
  • 正确 - 连接的右侧;这是任何FromClause对象,如Table对象,也可以是可选择兼容的对象,例如ORM映射类。
  • onclause – a SQL expression representing the ON clause of the join. 如果留在None,则FromClause.join()将尝试基于外键关系来连接两个表。
  • 完整 -

    如果为True,则渲染一个FULL OUTER JOIN,而不是LEFT OUTER JOIN。

    版本1.1中的新功能

也可以看看

FromClause.join()

Join

params * optionaldict** kwargs T5>
inherited from the params() method of ClauseElement

返回带有bindparam()元素的副本。

返回此ClauseElement的一个副本,其中bindparam()元素替换为从给定字典中取得的值:

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key T0> ¶ T1>
继承自 primary_key 属性 FromClause

返回构成此FromClause主键的Column对象的集合。

replace_selectable(old, alias)

用给定的Alias对象替换所有出现的FromClause'old',并返回这个FromClause的副本。

标量 * multiparams** params T5>
inherited from the scalar() method of Executable

编译并执行此Executable,返回结果的标量表示。

选择 whereclause = None** params / T5>
inherited from the select() method of FromClause

返回这个FromClause的SELECT。

也可以看看

select() - general purpose method which allows for arbitrary column lists.

self_group T0> ( T1> 针对=无 T2> ) T3> ¶ T4>
inherited from the self_group() method of ClauseElement

对这个ClauseElement应用“分组”。

子类重写此方法以返回“分组”结构,即括号。In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another select(). (请注意,通常应使用Select.alias()方法创建子查询,因为许多平台需要命名嵌套的SELECT语句)。

由于表达式组合在一起,所以self_group()的应用程序是自动的 - 最终用户代码不需要直接使用此方法。Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

ClauseElement的base self_group()方法仅返回self。

tablesample(sampling, name=None, seed=None)
inherited from the tablesample() method of FromClause

返回此FromClause的TABLESAMPLE别名。

返回值是顶级tablesample()函数也提供的TableSample结构。

版本1.1中的新功能

也可以看看

tablesample() - 使用指南和参数

unique_params * optionaldict** kwargs T5>
inherited from the unique_params() method of ClauseElement

返回带有bindparam()元素的副本。

params()功能相同,除了将unique = True添加到受影响的绑定参数以便可以使用多个语句。