Multiple optional query parameters with PostgreSQL

眉间皱痕 提交于 2020-01-03 05:45:08

问题


I use PostgreSQL10 and I want to built queries that have multiple optional parameters.

A user must input area name, but then it is optional to pick none or any combination of the following
event, event date, category, category date, style

So a full query could be "all the banks (category), constructed in 1990 (category date) with modern architecture (style), that got renovated in 1992 (event and event date) in the area of NYC (area) ".

My problem is that all those are in different tables, connected by many-to-many tables, so I cannot do something like

SELECT * FROM mytable
WHERE (Event IS NULL OR Event = event) 

I dont know if any good will come if I just join four tables. I can easily find the area id, since it is required, but I dont know what the user chose, beside that.

Any suggestions on how to approach this, with Postgre?

Thanks


回答1:


It might be optimal to build the entire query dynamically and only join in tables that you know you're going to need in order to apply the user's filters, but it's impractical. You're better off creating a view on the full set of tables. Use LEFT OUTER JOINs to ensure that you don't accidentally filter out valid combinations and index your tables to ensure that the query planner can navigate the table graph quickly. Then query the view with a WHERE clause reflecting only the filters you want to apply.

If performance becomes a concern and you don't mind having non-realtime data, you could use a materialized view to cache the results. Materialized views can be indexed directly, but this is a pretty radical change so don't do this unless you have to.



来源:https://stackoverflow.com/questions/48142273/multiple-optional-query-parameters-with-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!