TinyDB - where 子句


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

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

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

让我们借助几个示例来了解“where”子句的用法。

学生数据库

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

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

让我们对主题字段使用“ where ”子句-

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

此查询将获取“主题”字段为“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"
   }
]