how left outer join in sqlalchemy?

为君一笑 提交于 2021-02-05 09:21:58

问题


I want implement left outer join in sqlalchemy. the sql query is like this:

select * from skills left join user__skill on user__skill.skill_id=skills.id and  user__skill.user_id=4

and what i wrote in sqlalchemy is :

skills = db.session.query(Skill, User_Skill.skill_id).\
            outerjoin(User_Skill, User_Skill.skill_id==Skill.id and User_Skill.user_id==4).\
            order_by(Skill.name).all()

but it doesn't filter for a user and show all users skills.

how can i write this code?


回答1:


EDIT: Use and_ from sqlalchemy to join join conditions

from sqlalchemy import and_

skills = db.session.query(Skill, User_Skill.skill_id).\
            outerjoin(User_Skill, and_(User_Skill.skill_id==Skill.id, 
                                       User_Skill.user_id==4)).\
            order_by(Skill.name).all()

Old, wrong answer (different results):

Use .filter to limit your results. Change your query to:

skills = db.session.query(Skill, User_Skill.skill_id).\
            outerjoin(User_Skill, User_Skill.skill_id==Skill.id).\
            filter(User_Skill.user_id==4).\
            order_by(Skill.name).all()


来源:https://stackoverflow.com/questions/55257893/how-left-outer-join-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!