访问数据库
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时,访问不会让你在where子句中使用常规连接。这可能是为了让你购买更昂贵的软件。” - (Is the join expression not supported by MS Access?)
并非如此。从一些例子我尝试了我得出的结论:
Access不允许您将外部联接(LEFT / RIGHT)与一个或多个INNER JOINS一起使用。 约翰卡马克的名字我能做什么? 我想避免单独的选择查询。 请帮忙......
答案 0 :(得分: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