Peewee – 子查询

Peewee – 子查询

在SQL中,子查询是在另一个查询的WHERE子句中嵌入的查询。我们可以在外层model. select() 语句的where属性中作为参数实现子查询。

为了演示子查询在Peewee中的使用,让我们使用定义好的以下模型 –

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

在创建表格后,它们被填充了以下的样本数据 —

联系人表

联系人表的内容如下

Peewee - 子查询

为了从联系人表中只显示为ETC教员注册的RollNo的姓名和城市,下面的代码生成了一个SELECT查询,在其WHERE子句中有另一个SELECT查询。

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

上述代码将显示以下结果:

RollNo and City for Faculty='ETC'
RollNo:103 City:Indore
RollNo:104 City:Nasik
RollNo:108 City:Delhi
RollNo:110 City:Nasik

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程