Oracle:如何查询数据,以便结果集包含表B中相应列旁边的表A中的列?

时间:2015-08-19 08:05:12

标签: sql oracle

我有三张表,如截图中所示:

我需要查询表格,以便TAXINSURANCEBENEFIT列返回其描述旁边:

以下是一个查询,其中显示了其说明旁边的税码列:

查询:

SELECT A.*, B.TAX, C.REQ_CODE_DESC AS TAX_DESC, B.INSURANCE, B.BENEFIT 

FROM BUSINESS A INNER JOIN LICENSE_REQ B ON A.LICENSE_ID = B.LICENSE_ID

LEFT JOIN LICENSE_REQ_DESC C ON B.TAX = C.REQ_CODE

LEFT JOIN LICENSE_REQ_DESC C ON B.INSURANCE = C.REQ_CODE;

表格

BUSINESS - Primary Key LICENSE_ID

enter image description here

LICENSE_REQ - Foreign Key LICENSE_ID

enter image description here

LICENSE_REQ_DESC - Primary Key SEQ_NBR

enter image description here

这是resultset屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

您必须多次加入LICENSE_REQ_DESC表格(对于您要展示的每个说明一次),以不同方式对其进行别名

您的最终查询可能看起来像

SELECT bus.LICENSE_ID, 
  bus.BEGIN_DATE, 
  bus.END_DATE, 
  lr.TAX, 
  lrtax.REQ_DESC AS "TAX_DESC", 
  lr.INSURANCE, 
  lrins.REQ_DESC AS "INSURANCE_DESC", 
  lr.BENEFIT, 
  lrben.REQ_DESC AS "BENEFIT_DESC"
FROM BUSINESS bus
  JOIN LICENSE_REQ lr 
    ON (bus.LICENSE_ID = lr.LICENSE_ID)
  LEFT OUTER JOIN LICENSE_REQ_DESC lrtax 
    ON (lr.TAX = lrtax.REQ_CODE)
  LEFT OUTER JOIN LICENSE_REQ_DESC lrins 
    ON (lr.INSURANCE = lrins.REQ_CODE)
  LEFT OUTER JOIN LICENSE_REQ_DESC lrben 
    ON (lr.BENEFIT = lrben.REQ_CODE)

我将外部联接放到LICENSE_REQ_DESC表中,以确保即使其中TAXINSURANCEBENEFIT字段之一没有,也始终返回一行描述。如果不是这种情况,您可以使用常规联接安全地替换它们