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.
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 = ...
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 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.
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.
query = (
sa.select(['*']).
select_from(a
.join(x, a.c.id == x.c.x)
.join(y, a.c.id == y.c.y)
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With