Tinydb 简明教程

TinyDB - The where Clause

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

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

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

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

The Student Database

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

[
   {
      "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 " 子句 -

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

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

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

Example 2

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

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

此查询将获取到所有 "mark" 字段不等于 "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"
   }
]