Any Quicker Option Than Oracle Database Union

2019-05-19 17:36发布

I have a table that has multiple columns which store a text value. For example:

ID    FATHER_NAME    MOTHER_NAME
--------------------------------
1     Henry          Sarah
2     Martin         Rebecca
3     Martin         Nancy

I want to get all of the names in the table. I know I can do a union to do this:

(SELECT FATHER_NAME FROM MY_TABLE)
UNION
(SELECT MOTHER_NAME FROM MY_TABLE)

However, in my real table there are 15 columns I need to union and the query is obviously taking awhile (approximately 12 seconds). And I still need to do joins on these names, etc. Is there any other alternative to doing unions?

FYI: I am using Oracle.

1条回答
够拽才男人
2楼-- · 2019-05-19 17:51

If you are using Oracle 11g, you can use the UNPIVOT function:

select id, value, col
from yourtable
unpivot
(
  value for col in (FATHER_NAME, MOTHER_NAME) -- other columns will go here
) u;

See SQL Fiddle With Demo

Or you can use UNION ALL instead of UNION the difference is you will not get DISTINCT values:

select id, FATHER_NAME value, 'FATHER_NAME' col
from yourtable
union all
select id, MOTHER_NAME value, 'MOTHER_NAME' col
from yourtable

See SQL Fiddle With Demo

The UNION might be slower due to it attempting to get the DISTINCT values.

查看更多
登录 后发表回答