Maximize Database View With Multiple Or Statement

只愿长相守 提交于 2019-12-25 02:19:57

问题


I am trying to write a database view that selects from 2 tables. Here is an example:

USER_TABLE
- ID
- USER_NAME

FAMILY_TABLE
- ID
- FAMILY_NAME
- FATHER_USER_NAME
- MOTHER_USER_NAME
- GRANDFATHER_1_USER_NAME
... (multiple user name columns)

(The table writers didn't associate via ID for some reason)

I essentially need to make a view that has each user listed, along with the names of the families they belong to. I have tried a number of things, but each seems to fail.

I first tried to union SELECT statements from the FAMILY_TABLE, but that took forever (see my previous post).

Then I tried to do an "or join":

SELECT ut.USER_NAME, ft.FAMILY_NAME
FROM USER_TABLE ut
LEFT OUTER JOIN FAMILY_TABLE ft ON
(
    UPPER(ut.USER_NAME) = UPPER(ft.FATHER_USER_NAME)
    OR
    UPPER(ut.USER_NAME) = UPPER(ft.MOTHER_USER_NAME)
    ... (etc)
)

But that also takes a long time (took 22 seconds with just FATHER_USER_NAME and MOTHER_USER_NAME).

Can anyone suggest the most efficient way to write the query for the view I need? I am not sure how to make it quick.

FYI: Using Oracle 10g.


回答1:


Add function-based index on UPPER(USER_NAME) and UPPER(FATHER_USER_NAME), UPPER(ft.MOTHER_USER_NAME) ...

This should solve your problem.

Could you paste your execution plan?




回答2:


This apparently works quickly (about 500 ms):

SELECT ut.USER_NAME, familyInfo.FAMILY_NAME
FROM USER_TABLE ut
LEFT OUTER JOIN
(
    SELECT
    (
        UPPER(ft.FATHER_USER_NAME) || ',' || 
        UPPER(ft.MOTHER_USER_NAME) || ',' || 
        ... (etc)
    ) AS MEMBERS,
    ft.*
    FROM FAMILY_TABLE ft
) familtyInfo
ON familyInfo.MEMBERS LIKE ('%' || UPPER(ut.USER_NAME) || '%');


来源:https://stackoverflow.com/questions/13034983/maximize-database-view-with-multiple-or-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!