我需要加入3个数据表才能生成一个表并显示以下字段: u.master_id,p.surname,p.forename1,c.number,u.status
以下是表格详情:
Table 1 (person p)
Field name = entity_id (number)
Field name = surname(text)
Field name = forename1(text)
Field name = auditflag
Table 2 (users u)
Field name = master_id (number)
Field name = email (number)
Field name = status (text)
Field name = auditflag
Table 3 (contact c)
Field name = master_id (number)
Field name = entity_id (number)
Field name = number (text = holds the actual email address)
Field name = auditflag
表2和3中的master_id字段链接到人entity_id(master_id = p.entity_id)
表2中的电子邮件字段链接到表3中的entity_id(u.email = c.entity_id)以获取数字
auditflag用于将每个标记标记为活动记录,即(p.auditflag = 1 AND u.auditflag = 1 AND c.auditflag = 1)
我正在使用Excel 2010 VBA - 加入PostGreSQL数据库以获取数据。 下面是我用来加入2个表的代码,但是我的问题是" email"仅显示一个数字,因为实际地址位于名为" number"的字段下的第3个表(联系人)中。
我不知道如何包含第3个表格以在我的查询中显示字段c.number。
Const sqlconnection = "Provider=oledb;"
Dim conn As New Connection
conn.ConnectionString = sqlconnection
conn.Open
Dim rs As Recordset
Dim prs As String
prs = "SELECT u.master_id, p.surname, p.forename1, u.email, u.status " _
& "FROM users u INNER JOIN person p ON u.master_id=p.entity_id " _
& "WHERE u.auditflag=1 AND p.auditflag=1 " _
& "ORDER BY u.master_id "
Set rs = conn.Execute(prs)
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
.Refresh
End With
答案 0 :(得分:0)
你拥有所有的作品;您需要做的就是将第三个表添加到查询中并选择所需的列。
Dim prs As String
prs = "SELECT u.master_id, p.surname, p.forename1, c.number as email, u.status " _
& "FROM users u INNER JOIN person p ON u.master_id=p.entity_id " _
& " INNER JOIN contact c ON c.master_id=p.entity_id and u.email=c.entity_id " _
& "WHERE u.auditflag=1 AND p.auditflag=1 AND c.auditflag=1 " _
& "ORDER BY u.master_id "
正如所写,此查询仅会获得具有有效(auditflag=1
)person
行和有效contact
行的用户。更改为左连接并将auditflag
检查移动到连接条件将允许返回所有三个表中没有活动行的用户。
作为旁注,我发现表格中的列名正在积极地反对,以便轻易理解它们的含义;如果可以,我建议重新考虑你正在使用的名字。