2左连接的语法在sqlite中加入
此查询运行良好,并给我一个这样的输出:
[(1, 9), (2, 12), (4, 14), (6, 14)]
query = """
SELECT users.id,
count(tasks.userId)
FROM users
LEFT JOIN tasks ON users.id = tasks.userId
WHERE tasks.completed = FALSE
GROUP BY users.id
"""
但是,当我添加另一个左JOIN时,它并不能给我准确的结果:
query = """
SELECT users.id,
count(tasks.userId), count(songs.userId)
FROM users
LEFT JOIN tasks ON users.id = tasks.userId
LEFT JOIN songs ON users.id = songs.userId
WHERE tasks.completed = FALSE
GROUP BY users.id
"""
结果看起来像这样:
[(1, 9, 10), (2, 12, 10), (4, 14, 10), (6, 14, 10)]
但是,我的结果看起来像这样:
[(1, 90, 90), (2, 120, 120), (4, 140, 140), (6, 140, 140)]
看起来像值任务x 10
as count(任务)和计数(歌曲) 我错过了什么?
count(tasks.userid)
的想法是查找用户ID匹配的任务数。
This query runs fine and gives me an output like this:
[(1, 9), (2, 12), (4, 14), (6, 14)]
query = """
SELECT users.id,
count(tasks.userId)
FROM users
LEFT JOIN tasks ON users.id = tasks.userId
WHERE tasks.completed = FALSE
GROUP BY users.id
"""
However, when I add another left join, it does not give me accurate results:
query = """
SELECT users.id,
count(tasks.userId), count(songs.userId)
FROM users
LEFT JOIN tasks ON users.id = tasks.userId
LEFT JOIN songs ON users.id = songs.userId
WHERE tasks.completed = FALSE
GROUP BY users.id
"""
The result should look like this:
[(1, 9, 10), (2, 12, 10), (4, 14, 10), (6, 14, 10)]
but instead, my result looks like this:
[(1, 90, 90), (2, 120, 120), (4, 140, 140), (6, 140, 140)]
which looks like the value of tasks x 10
as both, count(tasks) and count(song)
what am I missing out on?
The idea of count(tasks.userId)
was to find the number of tasks where the userId matched.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
任务
和歌曲
中分别汇总,然后将用户加入聚合的结果:我不确定您是否真的想要
>左
加入(至少对于表任务
),因为在您的代码中,您所说的第一个查询返回了您的期望,尽管它包含left
加入,加入实际上是内部
JOIN,因为条件wend tasks.completed = false
仅返回匹配行。Aggregate separately in
tasks
andsongs
and then joinusers
to the results of the aggregations:I'm not sure if you actually want
LEFT
joins (at least for the tabletasks
), because in your code, the 1st query that you say returns what you expect, although it contains aLEFT
join, the join is actually anINNER
join because the conditionWHERE tasks.completed = FALSE
returns only the matching rows.