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

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

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

db.search(where('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

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

db.search(where('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"
   }
]