将我的sql查询转换为sqlalchemy时遇到很多麻烦。我无法找到任何资源来做我想做的事情。
我要转换的查询是:
SELECT
COALESCE(d.manager_name, e.name) AS name,
COALESCE(d.department_name, e.department_name) AS department
FROM employee e
LEFT JOIN department d ON e.id = d.id
WHERE e.date = '2018-11-05'
在sqlalchemy中,我想到了:
query = self.session.query(
func.coalesce(Department.manager_name, Employee.name),
func.coalesce(Department.department_name, Employee.department_name)).join(Department,
Employee.id == Department.id,
).filter(
Employee.date == '2018-11-05',
)
但是请继续获取错误:
sqlalchemy.exc.InvalidRequestError: Can't join table/selectable 'Department' to itself.
为什么?!这些说法是准确的!
答案 0 :(得分:2)
由于Department
是查询中最左边的项目,因此对其进行联接。要控制联接中的第一个实体或“左”实体,请使用Query.select_from()
:
query = self.session.query(
func.coalesce(Department.manager_name, Employee.name),
func.coalesce(Department.department_name, Employee.department_name)).\
select_from(Employee).\
outerjoin(Department, Employee.id == Department.id).\
filter(Employee.date == '2018-11-05')
ORM教程的"Querying with Joins"和Query.join()
: "Controlling what to Join From"下也对此行为进行了解释。
您的查询构造也使用Query.join()
,尽管原始SQL具有LEFT JOIN
。在这种情况下,应使用Query.outerjoin()
或join(..., isouter=True)
。