Any Quicker Option Than Oracle Database Union

眉间皱痕 提交于 2019-12-08 00:25:40

问题


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:


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.



来源:https://stackoverflow.com/questions/12827525/any-quicker-option-than-oracle-database-union

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