在db2中优化查询

时间:2014-12-19 15:58:49

标签: sql database db2 subquery

我有两张桌子,

过滤,包含国家/地区 - 城市映射

+---------+-------+-------------+------------+
| Parent  | Child | Parent_Code | Child_Code |
+---------+-------+-------------+------------+
| Country | State | COUNT_ABC   | ST_XYZ     |
| Country | State | COUNT_POQ   | ST_TRE     |
| Country | State | COUNT_WER   | ST_QWE     |
| State   | City  | ST_XYZ      | CT_ABC     |
| State   | City  | ST_TRE      | CT_QWE     |
| State   | City  | ST_ZXC      | CT_ASD     |
+---------+-------+-------------+------------+

名称,每个名称_Code

+---------+---------------+---------------+
| Entity  |  Entity_Code  |  Entity_Name  |
+---------+---------------+---------------+
| Country | COUNT_ABC     | United States |
| Country | COUNT_POQ     | Australia     |
| Country | COUNT_WER     | India         |
| State   | ST_XYZ        | New_York      |
| State   | ST_TRE        | Queensland    |
| City    | CT_ASD        | Banglore      |
| City    | CT_QWE        |  Sydney       |
+---------+---------------+---------------+

现在我想写一下我有结果的查询,

+---------------+------------+-----------+
| Australia     | Queensland | Sydney    |
| United States | New York   | Buffalo   |
| United States | New Jersey | Princeton |
| India         | Karantaka  | Banglore  |
+---------------+------------+-----------+

如何为这件事写优化查询?我的查询看起来像这样

SELECT 
    DISTINCT
    R.Entity_Code AS COUNTRY_CODE,
    R.Entity_Name AS COUNTRY,
    SR.Entity_Code AS STATE_CODE,
    SR.Entity_Name AS STATE,
    C.Entity_Code AS CITY_CODE,
    C.Entity_Name CITY,
FROM
    NAMES C
LEFT OUTER JOIN
(
SELECT *
FROM
   FILTER F
LEFT OUTER JOIN
    NAMES C
    ON F.PARENT = C.Entity_Code
)SR ON C.Entity_Code  = SR.Child_Code
LEFT OUTER JOIN
(
 SELECT *
FROM
   FILTER F
LEFT OUTER JOIN
    NAMES C
    ON F.PARENT = C.Entity_Code
)R ON SR.Parent_COde = R.Child_Code
WHERE 
    COALESCE(R.Entity,'Country')='Country'  
    AND COALESCE(SR.Entity,'State')='State'  
   AND C.Entity = 'City'

是否可以优化它或缩短它。 注意:我正在使用DB2

提前感谢!!

1 个答案:

答案 0 :(得分:1)

您可以通过filter

进行自我加入来获取代码
select fp.parent_code as country_code, fp.child_code as state_code, fc.child_code as city_code
from filter fp join
     filter fc
     on fp.child_code = fc.parent_code;

以此为基础,您可以加入名称:

select ec.entity_name as country, es.entity_name as state, eci.entity_name as city
from filter fp left join
     filter fc
     on fp.child_code = fc.parent_code left join
     entity ec
     on ec.entity_code= fp.parent_code left join
     entity es
     on es.entity_code = fp.child_code left join
     entity eci
     on eci.entity_code = fc.child_code;

left join适用于可能没有匹配项的实体。