0

我正在尝试查询员工的地址(家庭和通讯地址)。

我的员工表是

Staff_ID, First_Name, Last_Name, Home_Adress, Corr_Address

对于地址表是

Address_ID, Line1, Line2, Line3, Post_Code

这两个地址都链接到 Address_ID。我已经阅读了该网站,似乎这种方法是联合或加入,我不太确定如何写下来。

SELECT First_Name, Last_Name, Home_Adress, Corr_Address FROM STAFF
UNION
SELECT Address_ID FROM ADDRESS
GROUP BY First_Name

一些帮助将不胜感激,谢谢!

4

1 回答 1

2

您需要到JOIN桌子上Address两次,一次获得 the HomeAddress,另一次获得Corr_Address

SELECT
  s.First_Name,
  s.Last_Name,
  ah.Line1     AS HomeLine1,
  ah.Line2     AS HomeLine2,
  ah.Line3     AS HomeLine3,
  ah.Post_Code AS HomePost_Code,
  ac.Line1     AS CorrLine1,
  ac.Line2     AS CorrLine2,
  ac.Line3     AS CorrLine3,
  ac.Post_Code AS corrPostCode
FROM Staff AS s
INNER JOIN address AS ah ON s.Home_Address = ah.address_ID
INNER JOIN address AS ac ON s.corr_address = ac.addressid;

更新:

如果您想在一个字段中组合每个地址的地址详细信息,您可以执行以下操作:

SELECT
  s."First_Name",
  s."Last_Name",
  ah."Line1" || ', ' || ah."Line2" || ', ' || ah."Line3" || ', ' || ah."Post_Code" AS HomeAddress,
  ac."Line1" || ', ' || ac."Line2" || ', ' || ac."Line3" || ', ' || ac."Post_Code" AS CorrAddress
FROM Staff s
INNER JOIN address ah ON s."Home_Adress" = ah."Address_ID"
INNER JOIN address ac ON s."Corr_Address" = ac."Address_ID";

在这里查看它的实际效果:

这会给你这样的东西:

| FIRST_NAME | LAST_NAME |                   HOMEADDRESS |                   CORRADDRESS |
------------------------------------------------------------------------------------------
|        foo |       bar | line11, line12, line13, 34222 |   line12, line22, line32, 653 |
|       foo2 |      bar2 | line13, line23, line33, 34545 | line14, line25, line35, 33452 |
于 2013-05-18T00:19:36.713 回答