【问题标题】:Write SQL query without knowing LHS and RHS in where clause在 where 子句中不知道 LHS 和 RHS 的情况下编写 SQL 查询
【发布时间】:2021-06-27 15:37:28
【问题描述】:

我有一个过滤器列表:[州、城市、大学]。

这里有几个过滤器:

'state' = "Tamil Nadu" / "Karnataka" / "Maharashtra" / "all"

过滤器

'city' = "Chennai" / "Kanyakumari" / "Madhurai" / "Bangalore" / "Mysore" / "Dharwad" / "Mumbai" / "Pune" / "all"

过滤器

" college" = any college in city / "all"

如果这些单个元素的值为“全部”,那么我不必将它们包含在 where 子句中。这意味着那些值不是“all”的元素必须包含在 where 子句中。

喜欢:

(If the filter "college" is "all")
Select college_name, branches from Colleges where state = state and city = city.

(If city and college is "all")
Select college_name, branches from Colleges where state= state.

(If all the filters have "all")
Select college_name, branches from Colleges.

如何做到这一点?请帮助我。

【问题讨论】:

  • 你使用的是哪个数据库?
  • 我正在使用 postgres sql

标签: sql dynamic where-clause


【解决方案1】:

您可以通过在 where 子句中检查参数来跳过参数:

Select college_name, branches 
from Colleges 
where (state = 'all' or "state" = @state)
  and (city = 'all' or "city" = @city)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多