sqlite 中 2 个左连接的语法
syntax for 2 left joins in 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
"""
但是,当我添加另一个左连接时,它没有给我准确的结果:
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)]
这看起来像 tasks x 10
的值一样,count(tasks) 和 count(song)
我错过了什么?
count(tasks.userId)
的想法是找到 userId 匹配的任务数。
分别在 tasks
和 songs
中聚合,然后将 users
加入到聚合结果中:
SELECT u.id,
COALESCE(t.count_tasks, 0) count_tasks,
COALESCE(s.count_songs, 0) count_songs
FROM users u
LEFT JOIN (
SELECT userId, COUNT(*) count_tasks
FROM tasks
WHERE completed = FALSE
GROUP BY userId
) t ON u.id = t.userId
LEFT JOIN (
SELECT userId, COUNT(*) count_songs
FROM songs
GROUP BY userId
) s ON u.id = s.userId;
我不确定你是否真的想要 LEFT
连接(至少对于 table tasks
),因为在你的代码中,你说的第一个查询 returns 如您所料,虽然它包含一个 LEFT
连接,但该连接实际上是一个 INNER
连接,因为条件 WHERE tasks.completed = FALSE
returns 只有匹配的行。
这个查询运行良好并给我这样的输出:
[(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
"""
但是,当我添加另一个左连接时,它没有给我准确的结果:
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)]
这看起来像 tasks x 10
的值一样,count(tasks) 和 count(song)
我错过了什么?
count(tasks.userId)
的想法是找到 userId 匹配的任务数。
分别在 tasks
和 songs
中聚合,然后将 users
加入到聚合结果中:
SELECT u.id,
COALESCE(t.count_tasks, 0) count_tasks,
COALESCE(s.count_songs, 0) count_songs
FROM users u
LEFT JOIN (
SELECT userId, COUNT(*) count_tasks
FROM tasks
WHERE completed = FALSE
GROUP BY userId
) t ON u.id = t.userId
LEFT JOIN (
SELECT userId, COUNT(*) count_songs
FROM songs
GROUP BY userId
) s ON u.id = s.userId;
我不确定你是否真的想要 LEFT
连接(至少对于 table tasks
),因为在你的代码中,你说的第一个查询 returns 如您所料,虽然它包含一个 LEFT
连接,但该连接实际上是一个 INNER
连接,因为条件 WHERE tasks.completed = FALSE
returns 只有匹配的行。