我正在尝试使用以下代码在R中使用RODBC查询Access数据库:
library(RODBC)
channel <- odbcConnectAccess("S:\\mypath\\PhysiPopDONOTTOUCH\\Physiology.mdb")
data <- sqlQuery( channel , paste ("select Endoscopy.*,
Histology.Diagnosis from Endoscopy JOIN PatientData ON
Endoscopy.HospNum_Id=PatientData.HospNum_Id JOIN Histology ON
Histology.HospNum_Id=PatientData.HospNum_Id WHERE histology.VisitDate
= Endoscopy.VisitDate"))
。这不成功,因为我收到错误:
[1] "42000 -3506 [Microsoft][ODBC Microsoft Access Driver] Syntax
error in FROM clause."
[2] "[RODBC] ERROR: Could not SQLExecDirect 'select Endoscopy.*,
Histology.Diagnosis from Endoscopy JOIN PatientData ON
Endoscopy.HospNum_Id=PatientData.HospNum_Id JOIN Histology ON
Histology.HospNum_Id=PatientData.HospNum_Id WHERE Histology.VisitDate
= Endoscopy.VisitDate'"
表Endoscopy
和Histology
与PatientData
表各有一对一。我在语法上做错了什么?
答案 0 :(得分:1)
MS Access SQL要求JOIN
配对括在括号中。此外,使用paste()
是为了消除在R中断行时出现的字符串值内的长空格。并考虑使用表别名来简明地引用表。也包括一个分号终止符(参见:When should I use semicolons in SQL Server?)。见下面的调整:
data <- sqlQuery(channel ,
paste("SELECT e.*, h.Diagnosis",
"(FROM PatientData p"
"INNER JOIN Endoscopy e p ON e.HospNum_Id = p.HospNum_Id)",
"INNER JOIN Histology h ON h.HospNum_Id = p.HospNum_Id",
"WHERE h.VisitDate = e.VisitDate;", sep=" "))