1

访问数据库

table contacts
--------------
id
surname
name


table relations
---------------
contact_id
relation_id

contact_id 和 relation_id 都是引用表联系人 id 的外键

如果当前联系人的关系存在,我想执行查询以获取联系人的姓/名和关系的姓/名。如果它不存在,我想获取联系人的姓/名和关系字段的空白值。

所有这些都在一个查询中

编辑:

我使用左连接。我正在使用 VB.NET 运行查询:

Dim myOleDbDataReader As OleDbDataReader = _
    New OleDbCommand( _
    "SELECT c.id           AS contact_id " & _
    "     , c.surname      AS contact_surname " & _
    "     , c.name         AS contact_name " & _
    "     , c2.id          AS related_id " & _
    "     , c2.surname     AS related_surname " & _
    "     , c2.name        AS related_name " & _
    "FROM ((contacts c " & _
    "LEFT JOIN relations r " & _
    "ON c.id = r.contact_id) " & _
    "INNER JOIN contacts c2 " & _
    "ON c2.id = r.relation_id)" _
    , connection).ExecuteReader()

我得到OleDbException:不支持加入表达式。

他们在另一篇文章中说:“当您在 FROM 子句中使用 LEFT/RIGHT/INNER JOINS 时,Access 不会让您在 where 子句中使用常规连接。这可能是故意让您购买更昂贵的软件。” - (MS Access 不支持连接表达式吗?

不完全是这样。从我尝试的一些示例中,我得出的结论是:

Access 不允许您将外部联接 (LEFT/RIGHT) 与一个或多个 INNER JOINS 一起使用。以约翰·卡马克的名义,我能做什么?我想避免单独的选择查询。请帮忙...

4

1 回答 1

3
SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , c2.id      AS related_id
     , c2.surname AS related_surname
     , c2.name    AS related_name
FROM contacts c
  LEFT JOIN relations r
    ON c.id = r.contact_id
  JOIN contacts c2
    ON r.relation_id = c2.id

以上不适用于MS-Access。

这略有不同(两个左连接)但它有效

SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , c2.id      AS related_id
     , c2.surname AS related_surname
     , c2.name    AS related_name
FROM contacts c
  LEFT JOIN
    ( relations r
      LEFT  JOIN contacts AS c2
        ON r.relation_id = c2.id
    )  
    ON c.id = r.contact_id

尽管有第二个LEFT JOIN,但它会给出相同的结果集,因为第二个 LEFT JOIN 涉及外键关系(从多 -> 一个的方向)。

要使用 INNER JOIN 进行 LEFT JOIN,您可以使用:

SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , g.id       AS related_id
     , g.surname  AS related_surname
     , g.name     AS related_name
FROM contacts c
  LEFT JOIN
    ( SELECT r.contact_id
           , c2.id      
           , c2.surname
           , c2.name 
      FROM relations r
        INNER JOIN contacts AS c2
          ON r.relation_id = c2.id
    )  AS g
    ON c.id = g.contact_id
于 2011-04-12T11:59:52.813 回答