我被困在将下面的查询转换为peewee中:
SELECT bID, taskCount
FROM
(
SELECT
block.id AS bID,
Count( task.id ) AS taskCount
FROM
block
LEFT JOIN task ON task.block_id = block.id
WHERE
block.id NOT IN ( ( SELECT task.block_id FROM task WHERE task.channel_id = '1' ) )
GROUP BY
block.id
) AS A
INNER JOIN ( SELECT task.block_id FROM task GROUP BY task.block_id ) AS B
我知道可以做到,但是我无法编写完整的解决方案,因为我不知道该如何处理别名(BID,TaskCount),然后再确切地使用联接!
这是我写的,显然没有用:
subquery1 = (Block.select(Block.id.alias('BID'),fn.COUNT(Task.id).alias('TaskCount'))
.join(Task,JOIN.LEFT_OUTER,Task.block_id == Block.id)
.where(Block.id.not_in(Task.select(Task.block_id).where(Task.channel_id=='1')))
.group_by(Block.id)
.alias('subquery1'))
subquery2 = (Task.select(Task.block_id).group_by(Task.block_id) )
query = subquery1.select(subquery1.c.BID,subquery1.c.TaskCount)
.join(subquery2, on=(subquery1.c.BID == subquery2.c.block_id))
编辑:我修复了一些错误。但是现在我应该从查询对象中得到什么呢? 如果我打印查询的行,我将面对:
peewee.InternalError: (1054, "Unknown column 'subquery1.BID' in 'field list'")
答案 0 :(得分:0)
我看到您在查询中缺少一些信息。您应指定:
我本人并不熟悉Peewee,但希望这会有所帮助。
答案 1 :(得分:0)
最后,经过一小段的反复后,我发现了一个问题,我的代码中有一个多余的部分将其删除。
subquery2 = (Task.select(Task.block_id).group_by(Task.block_id) )
query = subquery1.select(subquery1.c.BID,subquery1.c.TaskCount).join(subquery2, on=(subquery1.c.BID == Task.block_id))
正确的部分是:
subquery1 = (Block
.select(Block.id.alias('BID'),fn.COUNT(Task.id).alias('TaskCount')
).join(Task,JOIN.LEFT_OUTER,Task.block_id == Block.id)
.where(Block.id.not_in(Task.select(Task.block_id).where(Task.channel_id=='1')))
.group_by(Block.id)
.alias('subquery1')).order_by(fn.COUNT(Task.id))