Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly join same table multiple times using sqlalchemy core api?

I'm trying to join same table several times, using sqlalchemy core api.

Here is the code:

import sqlparse
import sqlalchemy as sa

meta = sa.MetaData('sqlite:///:memory:')

a = sa.Table(
    'a', meta,
    sa.Column('id', sa.Integer, primary_key=True),
)

b = sa.Table(
    'b', meta,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('x', sa.Integer, sa.ForeignKey(a.c.id)),
    sa.Column('y', sa.Integer, sa.ForeignKey(a.c.id)),
)

meta.create_all()

x = b.alias('x')
y = b.alias('y')

query = (
    sa.select(['*']).
    select_from(a.join(x, a.c.id == x.c.x)).
    select_from(a.join(y, a.c.id == y.c.y))
)

print(sqlparse.format(str(query), reindent=True))

Last statement produces following output:

SELECT *
FROM a
JOIN b AS x ON a.id = x.x,
            a
JOIN b AS y ON a.id = y.y

If I try to execute this query query.execute() I get error:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) ambiguous column name: main.a.id [SQL: 'SELECT * \nFROM a JOIN b AS x ON a.id = x.x, a JOIN b AS y ON a.id = y.y']

The question is, how can I get rid of , a? If I try to execute:

engine.execute('''
    SELECT *
    FROM a
    JOIN b AS x ON a.id = x.x
    JOIN b AS y ON a.id = y.y
''')

It works fine.

like image 809
sirex Avatar asked Jun 09 '15 15:06

sirex


People also ask

How do I join a table in SQLAlchemy ORM?

DEBUG) Base = declarative_base() class table_1(Base): __tablename__ = 'table_1' ID = Column(Integer) FIRST_NAME = Column(String(80),primary_key = True) LAST_NAME = Column(String(80)) class table_2(Base): __tablename__ = 'table_2' ID_1 = Column(Integer) FIRST_NAME_1 = Column(String(80),primary_key = True) LAST_NAME_1 = ...

How make SQLAlchemy faster?

Instead of returning entire model instances, SQLAlchemy can fetch only the columns we're interested in. This not only reduces the amount of data sent, but also avoids the need to instantiate entire objects. Working with tuples of column data instead of models can be quite a bit faster.

How do I join two tables in a flask SQLAlchemy?

How do I join two tables in Sqlalchemy? Python Flask and SQLAlchemy ORM Now we use the join() and outerjoin() methods. The join() method returns a join object from one table object to another. For example, following use of join() method will automatically result in join based on the foreign key.

What is lazy loading SQLAlchemy?

Lazy loading refers to objects are returned from a query without the related objects loaded at first. When the given collection or reference is first accessed on a particular object, an additional SELECT statement is emitted such that the requested collection is loaded.


1 Answers

query = (
    sa.select(['*']).
    select_from(a
                .join(x, a.c.id == x.c.x)
                .join(y, a.c.id == y.c.y)
                )
)
like image 169
van Avatar answered Sep 19 '22 22:09

van