使用sqlalchemy表达式语言,我希望从2表中选择ID。因此我需要使用标签。如何解决这个问题。我需要来自相关表的ID和所有其他属性值。代码段如下:
s1 = select([rt_issues.c.id.label('rt_issue_id'),
rt_issues,
queues.c.id.label('q_id'),
queues,
]).\
where(rt_issues.c.id == issue_id).\
select_from(rt_issues.
outerjoin(queues,
rt_issues.c.queue_id == queues.c.id))
rs1 = conn.execute(s1)
错误日志:
"尝试使用标签' select语句中的选项。" %key) InvalidRequestError:不明确的列名' id'在结果集中!尝试 ' use_labels'选择语句中的选项。
答案 0 :(得分:0)
我使用SQLAlchemy tutorial做了相同的用例。
>>> from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
>>> metadata = MetaData()
>>> users = Table('users', metadata,
... Column('id', Integer, primary_key=True),
... Column('name', String),
... Column('fullname', String),
... )
>>> addresses = Table('addresses', metadata,
... Column('id', Integer, primary_key=True),
... Column('user_id', None, ForeignKey('users.id')),
... Column('email_address', String, nullable=False)
... )
所有数据
In [36]: s = select([users.c.id, users, addresses.c.id, addresses]).select_from(users.outerjoin(addresses))
In [37]: conn.execute(s).fetchall()
2017-01-20 19:13:11,218 INFO sqlalchemy.engine.base.Engine SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address
FROM users LEFT OUTER JOIN addresses ON users.id = addresses.user_id
2017-01-20 19:13:11,218 - sqlalchemy.engine.base.Engine - INFO - SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address
FROM users LEFT OUTER JOIN addresses ON users.id = addresses.user_id
2017-01-20 19:13:11,219 INFO sqlalchemy.engine.base.Engine {}
2017-01-20 19:13:11,219 - sqlalchemy.engine.base.Engine - INFO - {}
Out[37]:
[(1, 'jack', 'Jack Jones', 1, 1, 'jack@yahoo.com'),
(1, 'jack', 'Jack Jones', 2, 1, 'jack@msn.com'),
(2, 'wendy', 'Wendy Williams', 3, 2, 'www@www.org'),
(2, 'wendy', 'Wendy Williams', 4, 2, 'wendy@aol.com')]
使用where
声明
In [42]: s = select([users.c.id, users, addresses.c.id, addresses]).where(users.c.id == 1).select_from(users.outerjoin(addresses, addresses.c.user_id == users.c.id))
In [43]: conn.execute(s).fetchall()
2017-01-20 19:23:41,153 INFO sqlalchemy.engine.base.Engine SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address
FROM users LEFT OUTER JOIN addresses ON addresses.user_id = users.id
WHERE users.id = %(id_1)s
2017-01-20 19:23:41,153 - sqlalchemy.engine.base.Engine - INFO - SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address
FROM users LEFT OUTER JOIN addresses ON addresses.user_id = users.id
WHERE users.id = %(id_1)s
2017-01-20 19:23:41,155 INFO sqlalchemy.engine.base.Engine {'id_1': 1}
2017-01-20 19:23:41,155 - sqlalchemy.engine.base.Engine - INFO - {'id_1': 1}
Out[43]:
[(1, 'jack', 'Jack Jones', 1, 1, 'jack@yahoo.com'),
(1, 'jack', 'Jack Jones', 2, 1, 'jack@msn.com')]
没有必要的标签