我使用SQLAlchemy核心(版本1.13.12)定义了两个表,这些表必须具有一对一(0..1)的关系:
things = sa.Table(
"things",
metadata,
sa.Column("sid", sa.Integer, primary_key=True),
sa.Column("info", sa.String)
)
thingsextra = sa.Table(
"thingsextra",
metadata,
sa.Column("sid", sa.Integer, sa.ForeignKey(things.c.sid), primary_key=True),
sa.Column("moreinfo", sa.String)
fullthings = sa.join(things, thingsextra, isouter=True)
我在“事物”表中插入了一个项目,但未在“ thingsextra”中插入。然后,我尝试对左外部联接进行选择:
query = fullthings.select().where(things.c.sid == sid)
result = conn.execute(query).fetchone()
我收到以下异常:
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'sid' in result set column descriptions
看起来好像不是将已定义的ForeignKey理解为同一件事,但是我不知道如何解决它。
最佳答案
执行查询时(查询本身可以),但是在尝试访问结果的sid
列时,不会发生报告的错误:
>>> result.sid
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'sid' in result set column descriptions
原因是您的SELECT包含两列具有相同
sid
名称的列,其中一列来自things
表,另一列来自thingsextra
,因为您已加入它们。您可以通过显示result.keys()
进行检查>>> result.keys()
['sid', 'info', 'sid', 'moreinfo']
由于
sid
上的thingsextra
列是sid
上things
的外键,因此可以从SELECT中删除此列,因此它仅包含一个sid
列。您可以使用with_only_columns
在查询中选择所需的列来完成此操作>>> query = fullthings.select().with_only_columns([things.c.sid, things.c.info, thingsextra.c.moreinfo]).where(things.c.sid == 1)
>>> result = connection.execute(query).fetchone()
>>> result.keys()
['sid', 'info', 'moreinfo']
>>> result.sid
1