TinyDB - where 子句

TinyDB 提供了"where"子句,您可以在搜索特定数据时使用它。 "where"子句有助于过滤掉不需要的数据。 借助"where"子句,您可以快速访问特定数据。

在使用"where"子句之前,我们需要先导入它。 "where"子句的语法如下 −

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

让我们通过几个示例来了解"where"子句的用法。

学生数据库

对于示例,我们将使用以下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"
   }
]

示例 1

让我们对 subject 字段使用"where"子句 −

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

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

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

示例 2

让我们看看"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"
   }
]