SQL 多连接语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7854969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:34:38  来源:igfitidea点击:

SQL multiple join statement

sqlms-access

提问by Sara

When I had only one inner join in my SQL statement, it worked perfectly. I tried joining a second table, and now I am getting an error that says there is a syntax error (missing operator). What is wrong here?

当我的 SQL 语句中只有一个内部联接时,它工作得很好。我尝试加入第二个表,现在我收到一条错误消息,指出存在语法错误(缺少运算符)。这里有什么问题?

adsFormView.SelectCommand = "SELECT * FROM [tableCourse] INNER JOIN [tableGrade] ON [tableCourse].[grading] = [tableGrade].[id] INNER JOIN [tableCourseType] ON [tableCourse].[course_type] = [tableCourseType].[id] WHERE [prefix]='" & myPrefix & "' AND [course_number]='" & myCourseNum & "'"

回答by Marc B

For multi-table joins, you have to nest the extra joins in brackets:

对于多表连接,您必须将额外的连接嵌套在括号中:

SELECT ...
FROM ((origintable
JOIN jointable1 ON ...)
JOIN jointable2 ON ...)
JOIN jointable3 ON ...

basically, for every extra table you join past the first, you need a bracket before the original 'FROM' table, and a closing bracket on the matching JOIN 'on' clause.

基本上,对于第一个加入的额外表,您需要在原始“FROM”表之前添加一个括号,并在匹配的 JOIN“on”子句上添加一个结束括号。

回答by mwolfe02

MS Access (specifically, Jet/ACE) requires parentheses with multiple joins. Try:

MS Access(特别是 Jet/ACE)需要带有多个连接的括号。尝试:

adsFormView.SelectCommand = _
    " SELECT * FROM ([tableCourse] " & _
    " INNER JOIN [tableGrade] " & _
    "     ON [tableCourse].[grading] = [tableGrade].[id]) " & _
    " INNER JOIN [tableCourseType] " & _
    "     ON [tableCourse].[course_type] = [tableCourseType].[id] " & _
    " WHERE [prefix]='" & myPrefix & "'" & _
    "   AND [course_number]='" & myCourseNum & "'"

回答by Abdollah

In spite of MS SQL Server, MS Access requires parentheses for a multiple JOIN statement. Basically, JOIN is an operation between two tables. When you have more than one JOIN, in fact, you are JOINing the result of the previous JOIN to another table. This logic is cascaded for any extra JOIN. For instance, if you have JOIN operations between 4 tables, you need to write it as follows:

尽管有 MS SQL Server,但 MS Access 要求多 JOIN 语句使用括号。基本上,JOIN 是两个表之间的操作。当你有多个 JOIN 时,实际上你是在将前一个 JOIN 的结果 JOIN 到另一个表中。对于任何额外的 JOIN,此逻辑都会级联。例如,如果你有 4 个表之间的 JOIN 操作,你需要这样写:

SELECT * FROM
    (
        ( Table1 JOIN Table2 ON Table1.column1 = Table2.column2) --result of JOIN is treated as a temp table
         JOIN Table3 ON Table1.column1 = Table3.column3
    ) --result of JOIN is treated as another temp table
    JOIN Table4 ON Table4.column4 = Table2.column2