Tinydb 简明教程
TinyDB - Logical AND
“逻辑与”运算符组合多个条件,如果满足所有条件,则求值为真。TinyDB 逻辑与运算符作用于数据库的两个查询。如果两个查询都为真,TinyDB 将获取所需数据。另一方面,如果其中任何一个查询为假,它将返回一个空白。
The "Logical AND" operator combines multiple conditions and evaluates to True if all the conditions are met. TinyDB Logical AND operates on two queries of a database. If both the queries are True, TinyDB will fetch the required data. On the other hand, if any one of the queries is False, it will return a blank.
Syntax
TinyDB Logical AND 的语法如下 −
The syntax of TinyDB Logical AND is as follows −
db.search((Query().(query1) & (Query().(query2)
这里, field 表示我们要访问的数据部分。 Query() 是我们名为 student 的 JSON 表创建的对象。如果两个条件都满足,它将获取数据,否则它将返回一个空白。
Here, field represents the part of data that we want to access. Query() is the object created of our JSON table named student. It will fetch the data if both the conditions met, otherwise it will return a blank.
让我们举几个例子,看看 Logial AND 是如何工作的。我们将使用我们在所有先前章节中使用的 student 数据库。
Let’s take a couple examples and see how Logial AND works. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看当我们在 “st_name=lakhan” 和 “subject=MYSQL” 字段上应用逻辑与时,我们的 TinyDB 学生数据库返回了什么 −
Let’s see what our TinyDB Student database returns when we apply Logical AND on "st_name=lakhan" and "subject=MYSQL" field −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search ((Query().st_name == 'lakhan') & (Query().subject == 'MySQL'))
此查询将仅获取学生姓名为“lakhan”且“subject”为“MySQL”的行。
This query will fetch only those rows where the student name is "lakhan" and the "subject" is "MySQL".
[{
'roll_number': 4,
'st_name': 'lakhan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]
Example 2
此示例中,让我们对“subject”和“roll_number”字段应用逻辑 AND −
In this example, let’s apply Logical AND on the "subject" and "roll_number" fields −
from tinydb import TinyDB, Query
student = Query()
db = TinyDB('student.json')
db.search((student.subject.search('M')) & (student.roll_number < 5))
此查询将获取其中“roll_number”小于“4”且“subject”以字母“M”开头的所有行。
This query will fetch all the rows where the roll_number is less than "4" and "subject" starts with the letter "M".
[{
'roll_number': 4,
'st_name': 'lakhan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]