oracle中行轉列函數

來源:互聯網
上載者:User

標籤:

一、問題描述

  有時在“相互關聯的子查詢中”需要查詢某個實體類對應的某個欄位有多個值,如果不做行專列查詢,會提示返回多個列的錯誤。例如:

  如所示,一個組合包,可能對應多個產品,需要你將所對應的多個產品都放到前台顯示。

二、解決方案

  表結構設計

  首先,我們這裡採用相互關聯的子查詢的方式來擷取結果:

  組合包和產品是一對多的關係,故一個組合包可以對應多個產品:

select (select listagg(pp.product_name,‘,‘) within group(order by  pp.product_name)from edu_group_product gpp,--組合包和產品關聯表edu_product pp--產品表where gpp.group_id = gp.group_idand gpp.product_id = pp.product_id) productsfrom edu_group gp--組合包表where gp.group_id = 1000;

  查詢時間:

該函數結構:

LISTAGG(欄位名,分隔字元) WITHIN GROUP( ORDER BY 欄位名)

三、說明

  1.想使用該函數,在原生oracle上試了一會,發現總提示我“未找到要求的關鍵字”,反覆核對關鍵字和欄位名稱,都無法解決。於是在伺服器一個曾使用過該方法的表結構中嘗試試用該方法,一次成功,瞬間明白可能是因為伺服器版本不同的原因。一查果然啊:

select wm_concat(name) name from user;--10g寫法select listagg(name,‘,‘) within group (order by name) name from user;--11g寫法

  2.使用wm_concat後果

select (select wm_concat(pp.product_name)from edu_group_product gpp,--組合包和產品關聯表edu_product pp--產品表where gpp.group_id = gp.group_idand gpp.product_id = pp.product_id) productsfrom edu_group gp--組合包表where gp.group_id = 1000;

  同樣的表結構,同樣的查詢要求,使用wm_concate()函數結果:

                

  試了幾次,最快是3秒多,大並發量下,要死人的。

  同樣,在10g的資料庫中試用該方法耗時也很長。

   

 

oracle中行轉列函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.