- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
不是 SQL 专家:
我目前正在实现一个搜索网络应用程序。用户将发送 GET request
到一个特定的Endpoint
.
Endpoint
将接受一组 URL Params
请求可以带有可选字段。例如 1、2 或 3 个字段。
我的数据库表 USER
看起来像这样。
+--------------+---------+------+-----+---------+----------------+
| id | firstName | lastName | email | zip | phone |
+--------------+---------+------+-----+---------+----------------+
现在 Web 应用程序将获得 GET Request
与 Phone
或 Zip
或 Email
.
我有两种解决方案,但看起来都很糟糕:
Solution 1:
有多个SQL Queries
和 Execute
他们根据我收到的 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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!