简体   繁体   English

如何在peewee的where子句中使用子查询?

[英]How to use a subquery in where clause in peewee?

I want to translate this to peewee: 我想将其翻译为peewee:

SELECT *
FROM posts
WHERE user_id IN
    (SELECT id
     FROM users
     WHERE country_id == 15
     ORDER BY created_at DESC
     LIMIT 20)

My code is: 我的代码是:

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))
)

I'm getting error: 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.ProgrammingError:(1064,“你在你的SQL语法错误;检查对应于你的MySQL服务器版本使用附近的‘正确的语法手册t2id )’第1行” )

Peewee output sql like: Peewee输出sql像这样:

SELECT `t1`.`id`,
       ...
       `t1`.`uuid`
FROM `posts` AS `t1`
WHERE (`t1`.`user_id` IN `t2`.`id`)

So close! 很近!

Post.select(Post).where(Post.user_id.in_(subquery))

You don't use subquery.c.id, unless you want to refer directly to the ID represented in the subquery. 除非要直接引用子查询中表示的ID,否则不要使用subquery.c.id。

Documented in many places, but here is an example that almost exactly matches yours: 在很多地方都有记录,但是这里有一个几乎与您完全匹配的示例:

http://docs.peewee-orm.com/en/latest/peewee/example.html#performing-subqueries http://docs.peewee-orm.com/zh-CN/latest/peewee/example.html#performing-subqueries

Read the docs, in other words. 换句话说,请阅读文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM