如何在 peewee 的 where 子句中使用子查询?
How to use a subquery in where clause in peewee?
我想将其翻译成 peewee:
SELECT *
FROM posts
WHERE user_id IN
(SELECT id
FROM users
WHERE country_id == 15
ORDER BY created_at DESC
LIMIT 20)
我的代码是:
subquery = User.select(User.id)\
.where(User.country_id == 15)\
.order_by(User.created_at.desc())\
.limit(20)
record = await manager.execute(
Post.select(Post).where(Post.user_id.in_(subquery.c.id))
)
我遇到错误:
peewee.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't2
.id
)' at line 1")
Peewee 输出 sql 喜欢:
SELECT `t1`.`id`,
...
`t1`.`uuid`
FROM `posts` AS `t1`
WHERE (`t1`.`user_id` IN `t2`.`id`)
太近了!
Post.select(Post).where(Post.user_id.in_(subquery))
您不使用 subquery.c.id,除非您想直接引用子查询中表示的 ID。
在很多地方都有记录,但这里有一个几乎与您的完全匹配的示例:
http://docs.peewee-orm.com/en/latest/peewee/example.html#performing-subqueries
换句话说,阅读文档。
我想将其翻译成 peewee:
SELECT *
FROM posts
WHERE user_id IN
(SELECT id
FROM users
WHERE country_id == 15
ORDER BY created_at DESC
LIMIT 20)
我的代码是:
subquery = User.select(User.id)\
.where(User.country_id == 15)\
.order_by(User.created_at.desc())\
.limit(20)
record = await manager.execute(
Post.select(Post).where(Post.user_id.in_(subquery.c.id))
)
我遇到错误:
peewee.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't2
.id
)' at line 1")
Peewee 输出 sql 喜欢:
SELECT `t1`.`id`,
...
`t1`.`uuid`
FROM `posts` AS `t1`
WHERE (`t1`.`user_id` IN `t2`.`id`)
太近了!
Post.select(Post).where(Post.user_id.in_(subquery))
您不使用 subquery.c.id,除非您想直接引用子查询中表示的 ID。
在很多地方都有记录,但这里有一个几乎与您的完全匹配的示例:
http://docs.peewee-orm.com/en/latest/peewee/example.html#performing-subqueries
换句话说,阅读文档。