sqlalchemy - Select columns and join from multiple tables using sqlalchemy
问题描述
I'm trying to do something that I thought should be simple in sqlalchemy using a select
statement. Basically I have two tables and I want to select a few columns from them and do a left outer join with a group by. In SQL this would look something like this:
SELECT
t1.id,
t1.name,
count(t2.id) as child_count
FROM parent t1
LEFT OUTER JOIN child t2
ON t1.id = t2.parent_id
GROUP BY t1.id, t1.name;
In sqlalchemy I can do something close, but not exactly right by doing this:
sqlalchemy.select(
t1.id,
t1.name,
sqlalchemy.func.count(t2.id)
).where(
t1.id==t2.parent_id
).group_by(
t1.id, t1.name
)
However, as soon as I start using .join
or .outerjoin
it seems to get confused and I can't seem to work out how to do it.
Any guidance? It seems like I am missing something obvious.
解决方案
推荐阅读
- testing - Gradle拒绝启动进程命令'cmd'
- javascript - Highcharts 格式图例名称
- watson - Watson Data Platform 中不提供工具选项
- tcp - 快速搜索本地网络中的设备(tcp)
- python - 遍历字典列表python
- android - 如果 TTS 不支持卡纳达语,如何播放卡纳达语文本?
- jakarta-mail - 已删除的邮件不会从垃圾箱中删除,因此删除不会(始终)永久删除它们
- javascript - 如何将 ng-model 的引用作为函数的参数传递?
- reactjs - 用于渲染动态元数据的打字稿定义库
- postgresql - 精确词全文搜索 postgresql