Home >Database >Mysql Tutorial >How to Efficiently Join Multiple Tables in SQLAlchemy with a Single Query?

How to Efficiently Join Multiple Tables in SQLAlchemy with a Single Query?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 00:09:41710browse

How to Efficiently Join Multiple Tables in SQLAlchemy with a Single Query?

Joining Multiple Tables in SQLAlchemy Using One Query

SQLAlchemy allows for efficient data retrieval by joining multiple tables with a single query. To join several tables, it requires you to define relationships between the classes representing the tables in your database.

In your case, you have three classes: User, Document, and DocumentsPermissions. Let's establish relationships between these classes:

class User(Base):
    __tablename__ = 'users'
    email = Column(String, primary_key=True)
    name = Column(String)

class Document(Base):
    __tablename__ = "documents"
    name = Column(String, primary_key=True)
    author = Column(String, ForeignKey("users.email"), nullable=False)

class DocumentsPermissions(Base):
    __tablename__ = "documents_permissions"
    readAllowed = Column(Boolean)
    writeAllowed = Column(Boolean)

    document = Column(String, ForeignKey("documents.name"), nullable=False)

With these relationships, you can retrieve the desired table using a single query:

query = session.query(User, Document, DocumentsPermissions) \
    .filter(User.email == Document.author) \
    .filter(Document.name == DocumentsPermissions.document) \
    .filter(User.email == "[email protected]") \
    .all()

This query joins User, Document, and DocumentsPermissions tables by their relationships and filters the results based on email. The final result will be a list of tuples containing data from all three tables, as you described. By using this method, you can efficiently retrieve data from multiple tables with a single database query.

The above is the detailed content of How to Efficiently Join Multiple Tables in SQLAlchemy with a Single Query?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn