mysql SQLALSCHENY JOIN仅从第一个表返回结果

ercv8c1e  于 2022-12-10  发布在  Mysql
关注(0)|答案(2)|浏览(176)

这就是我的问题,我有以下表格:

class ClientCampaings(Base):

__tablename__ = 'client_campaign'

campaign_id = Column(INTEGER, primary_key=True)
client_id = Column(VARCHAR(50))
campaign_name = Column(VARCHAR(45))
campaign_status = Column(VARCHAR(45))
campaign_type = Column(VARCHAR(45))
registration_date = Column(DATE)

class ClientKpi(Base):

__tablename__ = 'client_kpi'

kpi_id = Column(INTEGER, primary_key=True)
kpi_name = Column(VARCHAR(45))
cost_conv = Column(FLOAT)
quality_score = Column(FLOAT)


class KpiAssigment(Base):

__tablename__ = 'kpi_assigment'

assigment_id = Column(INTEGER, primary_key=True)
kpi_id = Column(INTEGER, ForeignKey("client_kpi.kpi_id"))
campaign_id = Column(INTEGER, ForeignKey("client_campaign.campaign_id"))
assigned_by = Column(VARCHAR(45))
timestamp = Column(TIMESTAMP)

#Basic One To Many relation
client_campaign = relationship("ClientCampaings")
client_kpi = relationship("ClientKpi")

我对他们进行以下查询:

from database.session import MySqlConnection
from database.models import KpiAssigment,ClientKpi

db = MySqlConnection(database='db_goes_here').db_session()

kpi=db.query(KpiAssigment)\
      .join(ClientKpi)\
      .filter(KpiAssigment.kpi_id==ClientKpi.kpi_id).all()

我原以为会是这样的:

SELECT kpi_assigment.*,
       client_kpi.*
FROM kpi_assigment
INNER JOIN client_kpi
ON kpi_assigment.kpi_id=client_kpi.kpi_id

但是,当我运行SqlAlChemy查询时,我只得到第一个表的结果:

{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x7fb3d0ace910>, 'kpi_id': 1, 'assigned_by': 'xxx@email.net', 'assigment_id': 2, 'campaign_id': XXXXXXXXX, 'timestamp': datetime.datetime(2022, 12, 7, 17, 5, 8)}

我希望得到一个内部联接,也有来自ClientKpi表的数据。
我读了这些相关的问题,但仍然找不到为什么这不起作用
SqlAlchemy Outer Join Only Returns One Table
How to join data from two tables in SQLAlchemy?
我确实遵循了他们的文档
Https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.join
有什么想法吗?
谢谢

xtfmy6hx

xtfmy6hx1#

该查询

kpi=db.query(KpiAssigment)\
      .join(ClientKpi)\
      .filter(KpiAssigment.kpi_id==ClientKpi.kpi_id).all()

将仅选择KpiAssignemnt表;要选择相应的ClientKpi,请在query中包括ClientKpi型号:

kpi=db.query(KpiAssigment, ClientKpi).join(ClientKpi)

.filter是多余的,因为SQLAlChemy将使用声明的外键来创建JOIN
如果要循环遍历每个父对象的子对象,则可以使用没有显式联接的关系:

for client_kpi in some_kpi_assignment.client_kpi:
    # do something
dffbzjpn

dffbzjpn2#

我还在试着找出是否有更好的回应,同时,我做了以下事情,并得到了我想要的:

query = db.query(KpiAssigment.campaign_id, 
                  ClientKpi.cost_conv,
                  ClientKpi.quality_score)\
                  .join(ClientKpi)\
                  .filter(KpiAssigment.kpi_id==ClientKpi.kpi_id)\
                  .all()

它返回具有元组列表的结果:

print(query)

>>>[(1, 6.0, 2), (2, 6.0, 2)]

相关问题