终于该敲机房收费系统的难点之一组合查询了, 首先参考学生中的组合查询,但是我觉得这里的组合查询好像比学生中的难。。。在这需要判断的条件太多了,,,我自己屡了半天才屡清楚这个组合查询的思路。但是在写的时候老是出错,于是我参考好多人的博客,用什么方法的都有,在这里我先附上几个师哥师姐还有本期大神的关于组合查询的博客吧:
九期陈丽娜师姐:http://blog.csdn.net/jly4758/article/details/8195535 试了一下,这个方法还是不错的。
九期左荣华师姐:http://blog.csdn.net/zuozuo1245/article/details/7959542 自我感觉这个代码有点多。。。
12期周士豪大神:http://blog.csdn.net/z15732621736/article/details/47070929 逻辑分的很清楚。
经过我的试验,我决定选取一种自我认为比较简单的方法:
首先根据这个图我来分析一下查询条件的嵌套关系:
思路清楚了,就可以开始写代码了:(下边是代码)
Dim txtSQL As String
Dim mrc As ADODB.Recordset
Dim MsgText As String
Dim a
Select Case Combozuhe1 ’将与或关系转化一下,
Case "或"
a = "or "
Case "与"
a = "and "
End Select
Select Case Combozuhe2
Case "或"
a = "or "
Case "与"
a = "and "
End Select
txtSQL = "select * from worklog_Info where "
'判断第一行是否完整
If Trim(Comboziduan1.Text = "") Or Trim(Combocaozuo1.Text = "") Or Trim(txtQuery1.Text = "") Then
MsgBox "请把查询条件填写完整!", vbInformation, "提示"
Exit Sub
Else
'如果完整,开始查询
txtSQL = txtSQL & FieldName(Trim(Comboziduan1.Text)) & Trim(Combocaozuo1.Text) & "'" & Trim(txtQuery1.Text) & "'"
If Not Trim(Combozuhe1.Text) = "" Then '如果第一个组合框不为空
'判断第二行是否为空
If Trim(Comboziduan2.Text = "") Or Trim(Combocaozuo2.Text = "") Or Trim(txtQuery2.Text = "") Then
MsgBox "请把第二行的查询条件填写完整!", vbInformation, "提示"
Exit Sub
Else
'如果第二行完整,开始查询
txtSQL = txtSQL & a & FieldName(Trim(Comboziduan2.Text)) & Trim(Combocaozuo2.Text) & "'" & Trim(txtQuery2.Text) & "'"
If Not Trim(Combozuhe2.Text) = "" Then '如果第二个组合框不为空
'判读第三行是否完整
If Trim(Comboziduan3.Text) = "" Or Trim(Combocaozuo3.Text) = "" Or Trim(txtQuery3.Text) = "" Then
MsgBox "请把第三行的查询条件填写完整!", vbInformation, "提示"
Exit Sub
Else
'如果第三行不为空,开始查询
txtSQL = txtSQL & a & FieldName(Trim(Comboziduan3.Text)) & Trim(Combocaozuo3.Text) & "'" & Trim(txtQuery3.Text) & "'"
End If
End If
End If
End If
End If
Set mrc = ExecuteSQL(txtSQL, MsgText)
With MSHFlexGrid1
.Rows = 1
If mrc.EOF Then ‘在 '如果不存
MsgBox "没有查询到内容!", vbInformation, "提示"
Else
Do While Not mrc.EOF '查询的内容存在
'显示查询内容
.Rows = .Rows + 1
.CellAlignment = 4
.TextMatrix(.Rows - 1, 0) = Trim(mrc.Fields(0))
.TextMatrix(.Rows - 1, 1) = Trim(mrc.Fields(1))
.TextMatrix(.Rows - 1, 2) = Trim(mrc.Fields(2))
.TextMatrix(.Rows - 1, 3) = Trim(mrc.Fields(3))
.TextMatrix(.Rows - 1, 4) = Trim(mrc.Fields(4))
.TextMatrix(.Rows - 1, 5) = Trim(mrc.Fields(5)) & " "
.TextMatrix(.Rows - 1, 6) = Trim(mrc.Fields(6)) & " "
.TextMatrix(.Rows - 1, 7) = Trim(mrc.Fields(7))
.TextMatrix(.Rows - 1, 8) = Trim(mrc.Fields(8))
mrc.MoveNext
Loop
End If
End With
mrc.Close
组合查询,只要是屡清楚关系和思路了,就不觉得很难了,不要被这么多的关系给吓到,只要写还是能写出来的。