douji5329 2018-02-16 04:54
浏览 117

未传递某些参数时,如何执行SQL查询过滤?

I've built a REST endpoint for listing items, /api/items, and it can be passed a few options via query params for filtering the result.

For example, GET /api/items?minPrice=30&maxPrice=100&minRating=4&onSale=true

How can I translate this into my SQL queries?

If I get a request with only maxPrice=50, then what about the other parameters? Let's just assume the following is my query -

select * from items 
where minPrice=(???) and maxPrice=50 and minRating=(???) and onSale=(???)

How do I "ignore" a filter if nothing was requested for it, and only filter on maxPrice=50? Is there a programmatic way to do this?

In my case, I am using postgres, so I have paramterized query with &1, &2, etc. with the values for each one.

  • 写回答

2条回答 默认 最新

  • dongnuo2879 2018-02-16 05:19
    关注

    You should provide meaningful default values, if the values are not provided in the REST call. e.g.

    minValue = 0 
    maxValue = <veryHighValue>
    minRating = 0
    onSale in (true, false)
    

    Or you can start with these default values, and override then with the ones provided from the REST call.

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?