Access查询中日期范围筛选失效问题求助——MRN关联查询无法按日期过滤记录
Access Query Issue: Date Range Filter Not Working with MRN Search
我一眼就看出问题出在你的WHERE子句逻辑优先级上——OR运算符的优先级比AND低,再加上括号没正确包裹条件,导致你的查询实际上会返回所有匹配MRN的记录,完全忽略了日期范围的限制。
问题拆解
原查询的WHERE子句最后那段Or (((DemographicsTable.MRN)=forms!DMVAForm!frmSearches!searchByMRNForm!cbMRN))是罪魁祸首:它相当于给查询开了个“后门”——只要MRN匹配,不管日期条件是否满足,这条记录都会被返回。另外,日期条件的括号也没把Between...Or...IsNull的逻辑作为一个整体和MRN条件绑定,进一步打乱了逻辑。
修正后的查询
把所有条件重新梳理,确保MRN匹配是必须满足的前提,日期条件作为可选的过滤项(要么在范围内,要么不限制日期):
SELECT DemographicsTable.MRN, DemographicsTable.[First Name], DemographicsTable.[Last Name], [Abuse Table].[Date of Event], [Abuse Table].[Staff Name(s)], [Abuse Table].Unit, [Abuse Table].Shift, [Abuse Table].Location, [Abuse Table].[Other Location], [Abuse Table].Incident, [Abuse Table].[Abuse Type], [Abuse Table].[Other Abuse Type], [Abuse Table].[Unsubstantial/ Substantial], [Abuse Table].Description, [Abuse Table].Medications, [Abuse Table].Diagnoses, [Abuse Table].Behaviors, [Abuse Table].Intervention FROM DemographicsTable INNER JOIN [Abuse Table] ON DemographicsTable.MRN = [Abuse Table].MRN WHERE -- 必须匹配指定MRN (DemographicsTable.MRN = forms!DMVAForm!frmSearches!searchByMRNForm!cbMRN) -- 同时满足日期条件:要么在范围里,要么不限制日期 AND ( [Abuse Table].[Date of Event] Between Forms!DMVAForm!frmSearches!searchByMRNForm!txtStartDate And Forms!DMVAForm!frmSearches!searchByMRNForm!txtEndDate OR Forms!DMVAForm!frmSearches!searchByMRNForm!txtStartDate Is Null ) ORDER BY DemographicsTable.MRN;
逻辑说明
- 首先锁定
MRN匹配这个核心条件,用括号明确它是必须满足的 - 然后把日期相关的两个情况(在范围内/不限制日期)包裹在同一个括号里,作为和MRN条件的“与”关系——只有同时满足MRN匹配且日期条件的记录才会被返回
- 去掉了原查询末尾那个多余的OR分支,它正是导致日期过滤失效的原因
测试建议
你可以先把表单参数替换成实际值(比如MRN='1234',StartDate=#2023-01-01#,EndDate=#2023-12-31#)直接在Access查询编辑器里运行,验证逻辑是否正确,没问题再放回表单里使用。
内容的提问来源于stack exchange,提问作者award19
相关产品推荐
相关产品推荐

