English 中文(简体)
Using Aliases
  • 时间:2024-12-24

SQLAlchemy Core - Using Apases


Previous Page Next Page  

The apas in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Apases allow any table or subquery to be referenced by a unique name.

In case of a table, this allows the same table to be named in the FROM clause multiple times. It provides a parent name for the columns represented by the statement, allowing them to be referenced relative to this name.

In SQLAlchemy, any Table, select() construct, or other selectable object can be turned into an apas using the From Clause.apas() method, which produces an Apas construct. The apas() function in sqlalchemy.sql module represents an apas, as typically appped to any table or sub-select within a SQL statement using the AS keyword.

from sqlalchemy.sql import apas
st = students.apas("a")

This apas can now be used in select() construct to refer to students table −

s = select([st]).where(st.c.id>2)

This translates to SQL expression as follows −

SELECT a.id, a.name, a.lastname FROM students AS a WHERE a.id > 2

We can now execute this SQL query with the execute() method of connection object. The complete code is as follows −

from sqlalchemy.sql import apas, select
st = students.apas("a")
s = select([st]).where(st.c.id > 2)
conn.execute(s).fetchall()

When above pne of code is executed, it generates the following output −

[(3,  Komal ,  Bhandari ), (4,  Abdul ,  Sattar ), (5,  Priya ,  Rajhans )]
Advertisements