【问题标题】:How to implement a combination search?如何实现组合搜索?
【发布时间】:2021-09-14 04:00:48
【问题描述】:

我正在开发一个 API 端点 (Python + Sqlite),它基于以下参数运行 SQL 查询:种族、性别、年龄、位置。然而,需要注意的是,所有这些参数都是可选的,并且参数的任何组合都是有效的。比如下面的请求都是有效的。

localhost:8000/api?age=10&gender=M

localhost:8000/api?race=Asian&age=3&location=US&gender=F

localhost:8000/api

我不确定如何最好地解决这个问题。这似乎是一个简单的逻辑难题,但我似乎无法理解它。所有这些之间的唯一区别是SQL 查询中的“Where”语句。

我将不胜感激任何建议或相关想法。对不起,如果我没有清楚地解释这个问题,我什至都在努力表达这个问题。谢谢。

【问题讨论】:

  • 您是否考虑过使用 ORM(如 SQLAlchemy、Peewee、Django 等……)?它们允许简单地执行此类查询,但另一方面需要为您的表建模。

标签: python sql logic


【解决方案1】:

您可以做的是根据传入请求中收到的参数构造 SQL 查询。 简单的伪代码:

SQLquery = "SELECT * FROM mytable "
if there are any parameters
    SQLquery = SQLquery + "WHERE "
any more parameters?
   SQLquery = SQLquery + " and "
if input request has age
    SQLquery = SQLquery + "age = " + agevalue
any more parameters?
   SQLquery = SQLquery + " and "
if input request has race 
    SQLquery = SQLquery + "race = " + racevalue   
any more parameters?
   SQLquery = SQLquery + " and "
if input request has gender 
    SQLquery = SQLquery + "gender = " + gendervalue     
any more parameters?
   SQLquery = SQLquery + " and "
if input request has location
    SQLquery = SQLquery + "location = " + locationvalue 
Use SQLquery to fetch data from database

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2012-08-14
    • 2015-07-30
    • 2019-01-07
    • 2017-05-30
    • 2013-03-30
    • 2011-04-08
    • 2021-01-08
    相关资源
    最近更新 更多