gpt4 book ai didi

java - 带有用于搜索 Web 应用程序的可选字段的 SQL 查询

转载 作者:可可西里 更新时间:2023-11-01 08:45:09 25 4
gpt4 key购买 nike

不是 SQL 专家:

我目前正在实现一个搜索网络应用程序。用户将发送 GET request到一个特定的Endpoint .

Endpoint将接受一组 URL Params请求可以带有可选字段。例如 1、2 或 3 个字段。

我的数据库表 USER看起来像这样。

+--------------+---------+------+-----+---------+----------------+
| id | firstName | lastName | email | zip | phone |
+--------------+---------+------+-----+---------+----------------+

现在 Web 应用程序将获得 GET RequestPhoneZipEmail .

我有两种解决方案,但看起来都很糟糕:

Solution 1:
  1. 有多个SQL QueriesExecute他们根据我收到的 URL 参数。

    Select * from User where phone=1111111111 and zip=12345 and email=test@email.com;

    Select * from User where phone=1111111111 and zip=12345;

    ...
    ...

等等.........我最终会有很多查询,这将是一个糟糕的实现。也不好维护。

Solution 2:

我正在考虑的其他解决方案是有一个方法,它将根据我收到的 URL 参数构建一个 SQL 查询。

例子:

buildSQLQuery(phone,zip,email){

String sql = "Select * from User where "

if(phone!=null && email!=null && zip!=null ){
sql = sql + "phone = " + phone + " and zip = " + zip + " and email = " + email;
}else if (phone!=null && email!=null && zip==null){
sql = sql + "phone = " + phone + " and email = " + email;
}
.......
......
And so on have all conditions and build that particular query.
}

我不喜欢这两种解决方案。

有没有一种方法可以编写单个 SQL 查询来处理上述所有情况。

如果 URL 参数值是 NULL那么这应该不会影响查询,我会得到我预期的结果。

在我的例子中,没有出现的可选值被设置为 NULL .

我可以实现这样的东西吗?

Select * from User where (if notNull (phone))(phone = phone ) and (if notNull (email))(email = email ) and (if notNull (zip))(zip = zip )

如果以上任何一个值为空,则不要在 where Condition 中使用该部分.

此外,我将始终存在一个字段,因此不会出现所有值都为空的情况。

我正在用 Java 和 Spring MVC 实现这个 Web 应用程序。如果有人能指导我正确的方向。

谢谢。

最佳答案

我认为还有一个可能的解决方案:

String sql = "Select * from User where 1=1 "

if(phone!=null){
sql += " and phone = " + phone ;}

if(email!=null){
sql += " and email = " + email ;}

if(zip!=null){
sql += " and zip = " + zip ;}

或者您可以尝试以下单个查询:

select * from User 
where (@phone is null OR phone = @phone) AND (@email is null OR email = @email) AND (@zip is null OR zip = @zip)

关于java - 带有用于搜索 Web 应用程序的可选字段的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com