Access UNION SQL查询语法错误,两表联合查询保存报错问题求助
UNION查询语法错误的几个核心原因
- 列数不匹配:UNION要求上下两个SELECT语句返回的列数完全相等,你第一条SELECT返回了11个字段,第二条SELECT仅返回6个字段,不符合UNION的语法规则。如果不需要保留第一张表的额外字段,可以删掉第一条SELECT里多余的字段;如果需要保留,第二条SELECT对应位置用
NULL补全,和前面对应列的数据类型保持一致即可。 - 括号不匹配:第二条查询的WHERE子句括号存在语法错误,原句:
左侧有3个左括号,仅闭合了1个,且WHERE (((tblHerbicideResults.reportno0=[forms]![frmlogging]![reportno]));reportno0字段后缺失右括号,修正后应为:
同时注意确认WHERE (((tblHerbicideResults.reportno0)=[forms]![frmlogging]![reportno]));reportno0是否为表中真实存在的字段,你关联条件用的是herbreportno,这里可能存在字段名笔误。 - 数字开头的字段名未转义:你用的是Access数据库(存在
[forms]!引用语法),数字开头的字段名需要用方括号包裹,tblHerbicideResults.24DResults需要改为tblHerbicideResults.[24DResults],否则会被识别为语法错误。 - 列数据类型不匹配:除了列数一致,UNION还要求上下两个SELECT对应位置的列数据类型兼容,比如第一条SELECT第三列是
element(通常为文本类型),第二条第三列是[24DResults](通常为数值类型),类型不兼容的话需要用CSTR()/CDBL()等函数做类型转换,同时建议给列加统一别名。
给你一个修正后的参考示例,假设你不需要保留第一张表的多余字段,统一返回6列:
SELECT tblMetalsResults.reportno, tblMetalsResults.sampleno, tblMetalsResults.element AS item1, tblMetalsResults.ElementResult AS item2, tblLogging.loBattery, tblLogging.loTest FROM tblLogging INNER JOIN tblMetalsResults ON tblLogging.ReportNo = tblMetalsResults.reportno WHERE tblMetalsResults.reportno=[forms]![frmlogging]![reportno] UNION SELECT tblHerbicideResults.herbreportno, tblHerbicideResults.sampleno, tblHerbicideResults.[24DResults] AS item1, tblHerbicideResults.D45TPResults AS item2, tbllogging.lobattery, tbllogging.lotest FROM tbllogging INNER JOIN tblHerbicideResults ON tbllogging.Reportno = tblHerbicideResults.herbreportno WHERE tblHerbicideResults.herbreportno=[forms]![frmlogging]![reportno];
内容的提问来源于stack exchange,提问作者ZacharyCook
相关产品推荐
相关产品推荐

