| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 678 人关注过本帖
标题:[讨论]多条件数据库查询的优化方法后错误
取消只看楼主 加入收藏
xzqsml
Rank: 2
等 级:论坛游民
帖 子:41
专家分:47
注 册:2008-6-15
结帖率:90.91%
收藏
已结贴  问题点数:10 回复次数:1 
[讨论]多条件数据库查询的优化方法后错误
多条件数据库查询的优化方法
假设有一个名为employee的表,现在我们要从其中查询数据,条件有三个,由用户动态选择

Name=A
Sex=B
Age =C

其中条件A、B、C之间是与的关系,A、B、C均为动态选择,可以取其中的一个、两个或三个,也可以一个都不选,当三个条件都不选择时则认为是无条件查询

按照通常的做法:

这样,最终的结果有8个,即有8条查询语句,分别是

  1.select * from employee;

  2.select * from employee where Age =C ;

  3.select * from employee where Sex=B;

  4.select * from employee where Sex=B and Age=C;

  5.select * from employee where Name=A;

  6.select * from employee where Name=A and Age=C;

  7.select * from employee where Name=A and Sex=B ;

  8.select * from employee where Name=A and Sex=B and Age=C;

  显然这是比较烦琐的,而且用到了多重嵌套IF语句,因而在条件增多时,其复杂程度将大大增加。对它进行优化,方法如下:
Dim Str_Result As String
Str_Result = ""
if A <> "" then
Str_Result="where Name =A"
end if
'----------------
if B <> "" then
if Str_Result="" then
Str_Result="where Sex=B"
else
Str_Result=Str_Result+"and Sex = B"
end if
end if
'-----------------
if C <> "" then
if Str_Result="" then
Str_Result="where Age =C"
else
Str_Result=Str_Result+"and Age=C"
end if
end if

 最终的结果查询语句为: SQL = "select * from employee + Str_Result"

为什么运行后,出现 "Form 子句语法错误" 提示



[ 本帖最后由 xzqsml 于 2010-1-29 10:17 编辑 ]
搜索更多相关主题的帖子: 查询 条件 数据库 
2010-01-29 10:03
xzqsml
Rank: 2
等 级:论坛游民
帖 子:41
专家分:47
注 册:2008-6-15
收藏
得分:0 
以下是引用xzqsml在2010-1-29 10:03:59的发言:

多条件数据库查询的优化方法
假设有一个名为employee的表,现在我们要从其中查询数据,条件有三个,由用户动态选择

Name=A
Sex=B
Age =C

其中条件A、B、C之间是与的关系,A、B、C均为动态选择,可以取其中的一个、 ...
经过自己的测试,好像可行...请朋友们再验证下..

'------------------
代码如下:

Dim Str_Result As String
Str_Result = "" '将变量为空

if A <> "" then
Str_Result = "Name =A"
end if
'----------------
if B <> "" then
if Str_Result = "" then
Str_Result = "Sex=B"
else
Str_Result = Str_Result + "and Sex = B"
end if
end if
'-----------------
if C <> "" then
if Str_Result = "" then
Str_Result = "Age = C"
else
Str_Result = Str_Result + "and Age=C"
end if
end if

最终结果:SQL = "select * from employee Where" + Str_Result
把Where 加在了SQL中,去除了If 中Where
Str_Result放在SQL引号外..


[ 本帖最后由 xzqsml 于 2010-1-29 10:46 编辑 ]
2010-01-29 10:44
快速回复:[讨论]多条件数据库查询的优化方法后错误
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019729 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved