多个连接语句的语法错误

时间:2017-12-06 14:13:51

标签: sql ms-access

您好,我在这个sql语句中遇到语法错误,任何人都可以建议谢谢

String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
    "FROM tblStudent LEFT JOIN tblSchool " +
    "ON (tblStudent.schoolID = tblSchool.schoolID) " +
    "LEFT JOIN tblAgents " +
    "ON (tblStudent.agentID = tblAgents.agentID) " +
    "WHERE tblStudent.StudentID='" + studentID + "'";

我希望我可以做多个连接

但我收到语法错误。

3 个答案:

答案 0 :(得分:1)

对于访问,具有多个连接的括号表示以下内容。如果你有三个连接,则从后面有两个左括号。最后一个连接没有右括号。

String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";

其他threads已涵盖Access SQL注入。

答案 1 :(得分:0)

        String sql = "Select 
        tblStudent.StudentID,tblStudent.studentFirstName,"+
        tblStudent.studentLastName,tblSchool.schoolName," + 
        tblAgents.agentFirstName,tblAgents.agentLastName " +
        "FROM (tblStudent LEFT JOIN tblSchool " +
        "ON (tblStudent.schoolID = tblSchool.schoolID)) " +
        "LEFT JOIN tblAgents " +
        "ON (tblStudent.agentID = tblAgents.agentID) " +
        "WHERE tblStudent.StudentID=@studentID";

答案 2 :(得分:0)

我相信你的最终SQL应该是这样的:

SELECT tblStudent.*
    ,tblSchool.*
    ,tblAgents.*
FROM tblSchool
RIGHT JOIN (
    tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID
    ) ON tblSchool.schoolID = tblStudent.schoolID
WHERE tblStudent.StudentID=111;

因此,用于创建此SQL的VBA代码应为

Dim sql As String

sql = "SELECT tblStudent.* ,tblSchool.* ,tblAgents.* " & _
    "FROM tblSchool RIGHT JOIN (" & _
    "tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID" & _
    ") ON tblSchool.schoolID = tblStudent.schoolID " & _
    "WHERE tblStudent.StudentID=" & studentID

这里我假设studentID是数字字段。另外,我建议不要使用*从多个表中选择数据,否则列名可能无法预测,并且如评论中所述,它将需要额外的资源,这些资源不会被使用。