Access-SQL:内部连接多个表

时间:2013-10-14 19:16:10

标签: sql ms-access vb6 ado

我在数据库中有多个表:

tblOjt

ID    studentid    courseid    companyid    addresseeid    dateadded    datestarted    dateended    ojthours

1         3            1           1             1         9/25/2013                                  500 

tblStudent

ID    lastname    firstname    middlename    course    gender    renderedhours    dateadded    archive

3     Dela Cruz      Juan        Santos       BSIT      Male          500

tblCourse

ID    coursealias    coursename                                            hours
1         BSIT      Bachelor of Science in Information Technology          500

tblCompany

ID    companyname

1      MyCompany

tblAddressee

ID    addresseename

1     John dela Cruz

我需要一个SQL语句,我可以在其中获取此值:

tableOjt.id  tableOJT.surname,firstname, and middlename  course  companyname  addresseename dateadded datestarted dateended ojthours

如何使用这些连接方法在SQL中获取此代码...我在VB6 ADODC中编写它,这是否与标准SQL中的语法相同?感谢

3 个答案:

答案 0 :(得分:58)

如果要针对Access数据库后端编写查询,则需要使用以下连接语法:

select
  t1.c1
, t2.c2
, t3.c3
, t4.c4
from ((t1
inner join t2 on t1.something = t2.something)
inner join t3 on t2.something = t3.something)
inner join t4 on t3.something = t4.something

这里的表名和列名并不重要,但括号的位置是。基本上,你需要在from子句之后有 n - 2 左括号,并且在每个新join子句开始之前有一个右括号,除了第一个,其中 n 是连接在一起的表的数量。

原因是Access的连接语法一次只支持连接两个表,因此如果需要连接两个以上,则需要将多余的表括在括号中。

答案 1 :(得分:2)

SELECT tblOjt.id, tblStudent.firstname, tblStudent.middlename, 
       tblStudent.lastname, tblStudent.course, tblCompany.companyname, 
       tblAddressee.addressee 
FROM (((tblOjt 
     INNER JOIN tblStudent ON tblOjt.studentid = tblStudent.id) 
     INNER JOIN tblCourse ON tblOjt.courseid = tblCourse.id) 
     INNER JOIN tblCompany ON tblOjt.companyid = tblCompany.id) 
     INNER JOIN tblAddressee ON tblOjt.addresseeid = tbladdressee.id
发现它!感谢Yawar的做法......

答案 2 :(得分:0)

一直在尝试使用VBA运行此SQL,但不会使用DoCmd.RunQuery运行。我已经尝试了SQL,但它正在工作。

str = "SELECT tbl_company.[Company], tbl_company.[Commodity], tbl_company.[Segment], tbl_company.[MainProduct]," & _
      " tbl_financials.[DataYear]," & _
      " mstr_financial.[FinancialData]," & _
      " tbl_financials.[Amount]," & _
      " tbl_financials.[Unit]," & _
      " tbl_company.[CompanyID]" & _
      " FROM (tbl_company" & _
      " INNER JOIN tbl_financials ON tbl_company.[CompanyID] = tbl_financials.[CompanyID])" & _
      " INNER JOIN mstr_financial ON tbl_financials.[FinID] = mstr_financial.[FinID] " & _
      " ORDER BY tbl_company.[Company], tbl_financials.[DataYear] DESC"