Peewee 简明教程
Peewee - Subqueries
在 SQL 中,子查询是另一个查询的 WHERE 子句中的嵌入式查询。我们可以将子查询实现为外层模型的 select() 语句的 where 属性中的一个 model.select() 作为参数。
In SQL, a subquery is an embedded query in WHERE clause of another query. We can implement subquery as a model.select() as a parameter inside where attribute of outer model.select() statement.
为了演示 Peewee 中的子查询用法,让我们使用以下定义的模型:
To demonstrate use of subquery in Peewee, let us use defined following models −
from peewee import *
db = SqliteDatabase('mydatabase.db')
class BaseModel(Model):
class Meta:
database = db
class Contacts(BaseModel):
RollNo = IntegerField()
Name = TextField()
City = TextField()
class Branches(BaseModel):
RollNo = IntegerField()
Faculty = TextField()
db.create_tables([Contacts, Branches])
在创建表后,用以下示例数据填充它们:
After tables are created, they are populated with following sample data −
Contacts table
contacts 表如下:
The contacts table is given below −


为了仅显示 ETC 教师注册过的 RollNo 的联系人和城市,以下代码会生成一个 SELECT 查询,其中 WHERE 子句中包含另一个 SELECT 查询。
In order to display name and city from contact table only for RollNo registered for ETC faculty, following code generates a SELECT query with another SELECT query in its WHERE clause.
#this query is used as subquery
faculty=Branches.select(Branches.RollNo).where(Branches.Faculty=="ETC")
names=Contacts.select().where (Contacts.RollNo .in_(faculty))
print ("RollNo and City for Faculty='ETC'")
for name in names:
print ("RollNo:{} City:{}".format(name.RollNo, name.City))
db.close()
以上代码将显示以下结果:
Above code will display the following result:
RollNo and City for Faculty='ETC'
RollNo:103 City:Indore
RollNo:104 City:Nasik
RollNo:108 City:Delhi
RollNo:110 City:Nasik