Am currently trying to convert an MySQL statement that I have written into using the functionality of SQLAlchemy
What I have is a table Project
and one for Likes
. These contain likes of the project. I want to get all of the specific user Projects and get the corresponding like counts.
This is the MYSQL:
SELECT project.id as id, project.name as name,
project.description as description,
project.user_id as user_id,
iFNULL(like_count,0) as like_count,
project.created_on
FROM milo.project LEFT JOIN (
SELECT COUNT(*) as like_count, project_id
FROM milo.likes
GROUP BY project_id
) counting
ON counting.project_id = milo.project.id
WHERE (milo.project.user_id = 1)
ORDER BY project.created_on
So this Joins a table Project
to another table created through a query which counts the likes of that project
This query gets the Like
counts:
res = db.session.query(func.count(likes.Likes.project_id), project.Project) \
.join(project.Project, (likes.Likes.project_id == project.Project.id)) \
.group_by(likes.Likes.project_id)
This query gets the user projects:
user_projects = Project.query.filter_by(user_id=1).all()
The closest I got to this, is the following:
projects = db.session.query(func.count(Likes.project_id), Project) \
.join(Project, (Project.id == Likes.project_id)) \
.filter(Likes.user_id == user.id) \
.group_by(Likes.project_id).order_by(Project.created_on.desc()) \
.all()
But the issue with this, is that if a Project has no likes, it is not returned! Clearly it also needs a Left Join, which I cannot find here.
Could anyone help with the translation of this statement?
I believe that you are searching for outerjoin .
so
.join(Project, (Project.id == Likes.project_id)) \
becomes
.outerjoin(Project, (Project.id == Likes.project_id))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.