Tinydb 简明教程

TinyDB - The where Clause

TinyDB 提供了 "where" 子句,你可以在检索特定数据时使用它。通过过滤掉不需要数据,"where" 子句能够提供帮助。借助 "where" 子句,你可以快速访问指定数据。

TinyDB provides the "where" clause that you can use while searching for a particular data. The "where" clause helps by filtering the unwanted data out. With the help of the "where" clause, you can access specific data quickly.

在使用 'where' 子句之前,我们需要先导入它。'where' 子句的 syntax 如下所示 −

Before using the 'where' clause, we need to first import it. The syntax of "where" clause is given below −

from tinydb import where
db.search(where('field') == 'value')

我们通过几个示例来理解如何使用 'where' 子句。

Let’s understand the use of 'where' clause with the help of a couple of examples.

The Student Database

对于示例,我们将使用以下 student 数据库。

For the examples, we will use the following student database.

[
   {
      "roll_number":1,
      "st_name":"elen",
      "mark":250,
      "subject":"TinyDB",
      "address":"delhi"
   },
   {
      "roll_number":2,
      "st_name":"Ram",
      "mark":[
         250,
         280
      ],
      "subject":[
         "TinyDB",
         "MySQL"
      ],
      "address":"delhi"
   },
   {
      "roll_number":3,
      "st_name":"kevin",
      "mark":[
         180,
         200
      ],
      "subject":[
         "oracle",
         "sql"
      ],
      "address":"keral"
   },
   {
      "roll_number":4,
      "st_name":"lakan",
      "mark":200,
      "subject":"MySQL",
      "address":"mumbai"
   },
   {
      "roll_number":5,
      "st_name":"karan",
      "mark":275,
      "subject":"TinyDB",
      "address":"benglore"
   }
]

Example 1

我们给 subject 字段使用 " where " 子句 -

Let’s use the "where" clause for the subject field −

db.search(where('subject') == 'MySQL')

此查询将获取到所有 "subject" 字段为 "MySQL" 的行。

This query will fetch all the rows where the "subject" field is "MySQL".

[{
   'roll_number': 4,
   'st_name': 'lakan',
   'mark': 200,
   'subject': 'MySQL',
   'address': 'mumbai'
}]

Example 2

让我们看另一个与 " not equal to " 条件一起使用 " where " 子句的用法 -

Let’s see another use of the "where" clause with the "not equal to" condition −

db.search(where('mark') != 275)

此查询将获取到所有 "mark" 字段不等于 "275" 的行。

This query will fetch all the rows where the "mark" field is not equal to "275" −

[
   {
      "roll_number":1,
      "st_name":"elen",
      "mark":250,
      "subject":"TinyDB",
      "address":"delhi"
   },
   {
      "roll_number":2,
      "st_name":"Ram",
      "mark":[
         250,
         280
      ],
      "subject":[
         "TinyDB",
         "MySQL"
      ],
      "address":"delhi"
   },
   {
      "roll_number":3,
      "st_name":"kevin",
      "mark":[
         180,
         200
      ],
      "subject":[
         "oracle",
         "sql"
      ],
      "address":"keral"
   },
   {
      "roll_number":4,
      "st_name":"lakan",
      "mark":200,
      "subject":"MySQL",
      "address":"mumbai"
   }
]