【问题标题】:How to use JOIN and SELECT AS together in SQLAlchemy?如何在 SQLAlchemy 中同时使用 JOIN 和 SELECT AS?
【发布时间】:2021-05-18 03:55:48
【问题描述】:

我有以下两个表格。

用户表

id name email
32 Hello e@mail.com
23 World p@mail.com

销售表

id SellerId CustomerId Amount
4 32 23 25

我想通过以下方式加入表格以获得此结果。在这里,我只想获取客户 ID 等于 23 的条目。

Id SellerId SellerName SellerEmail Amount
4 32 Hello. e@mail.com 25.

并且还以这种方式进行另一个连接。在这里,我只想获取卖家 ID 等于 32 的条目。

id CustomerId CustomerName CustomerEmail Amount
4 23 World p@mail.com 25.

我的两个表的代码是

class Users(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    email = Column(String, unique=True, index=True, nullable=False)

class Sales(Base):
    __tablename__="sales"

    id = Column(Integer, primary_key=True, index=True)
    seller_id = Column(Integer, index=True)
    customer_id = Column(Integer, index=True)
    amount = Column(Integer, index=True)

我能够通过以下方式使用原始 SQL 来实现这一点

SELECT (sales.id), name as SellerName, email as SellerEmail, Amount
FROM sales
LEFT JOIN user ON sales.SellerId = user.id
WHERE CustomerId = 23

请帮助使用 SqlAlchemy Session 做同样的事情。

【问题讨论】:

    标签: python sql join sqlalchemy


    【解决方案1】:
    query = (    
        session.query(
            Sales.id,
            Users.name.label('SellerName'),
            Users.email.label('SellerEmail'),
            Sales.amount
        )
        .select_from(Sales)
        .outerjoin(Users, Users.id == Sales.seller_id)
        .filter(Sales.customer_id == 23)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2018-10-05
      相关资源
      最近更新 更多