希望这将是一个简单的问题!
我有两个表,一个'client(s)'表和一个单独的'names'表。基础是客户端可以有一个或两个(最大)名称。我将它们构造成这样,以便每个'名称'可以有不同的标题。表格是:
clients
+------------+-------------+------------+
| clientID | nameID1 | nameID2 |
+------------+-------------+------------+
| 1 | 1 | 2 |
| 2 | 3 | |
| 3 | 4 | |
+------------+-------------+------------+
names
+------------+-------------+------------+------------+
| nameID | surname | initials | titleID |
+------------+-------------+------------+------------+
| 1 | Banks | P | 1 |
| 2 | Smith | W | 2 |
| 3 | Wilson | BT | 2 |
| 4 | Jefferson | JP | 3 |
+------------+-------------+------------+------------+
从...中检索titleID
titles
+------------+-------------+
| titleID | titleName |
+------------+-------------+
| 1 | Mr |
| 2 | Mrs |
| 3 | Miss |
+------------+-------------+
因此,例如clientID = 1是Mr P Banks'&' W Smith夫人
问题是我不熟悉查询以获得上述答案。
我无法尝试:
SELECT
clientID, names.surname, names.initials, titleName
FROM clients, names, titles
WHERE titleID = titleID AND
NameID1 = nameID AND
NameID2 = nameID
如何正确连接查询中的表以查找,例如,
clientID 1 = Mr P Banks '&' Mrs W Smith
答案 0 :(得分:2)
您需要两次加入名称(和标题)表,一次是nameID1,一次是nameID2。我假设客户端必须至少有一个名称,因此nameID1为INNER JOIN
,并且由于namedID2是可选的(可为空),因此它是LEFT OUTER JOIN
。
SELECT c.clientID, n1.surname, n1.initials, t1.titleName, n2.surname, n2.initials, t2.titleName
FROM clients c
INNER JOIN names n1 ON nameID1 = n1.nameID
INNER JOIN titles t1 ON n1.titleID = t1.titleID
LEFT OUTER JOIN names n2 ON nameID2 = n2.nameID
INNER JOIN titles t2 ON n2.titleID = t2.titleID