Oracle - 从多个列查询地址

时间:2013-05-18 00:16:37

标签: sql database oracle

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

员工表的内容是

Staff_ID, First_Name, Last_Name, Home_Adress, Corr_Address

对于地址表是

Address_ID, Line1, Line2, Line3, Post_Code

两个地址都链接到Address_ID。我已经阅读了网站,看来这个方法是Union或Join,我不确定如何写下来。

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

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

1 个答案:

答案 0 :(得分:2)

您需要JOINAddress两次,一次获取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 |