2009-11-10 33 views
1

考慮三個表:汽車表,演員表和鏈接表,是這樣的:的Oracle PL/SQL Denomalised結果

table_car 
--------- 
int car_id 
string make 
string model 

table_extras 
------------ 
int extra_id 
string extra 

table_car_extras_link 
--------------------- 
int car_id 
int extra_id 

我想編寫一個PL/SQL存儲過程返回數據用以下方式:

car_id, make, model, extra[] 

例如

1, Ford, Fiesta, sunroof;electric windows 
2, BMW, M3, sports pack;alarm;sat nav 
3, subary, impreza, leather seats;ABS 

對於數據庫,我是一個非常新手,所以任何幫助表示讚賞。請注意,在我們的實際系統中,我們將返回「車」的1000與每節車廂具有多達約10「附加」

回答

4

這應該只是一個觀點,沒有必要的程序:

create view myview as 
select c.car_id, c.make, c.model, WM_CONCAT(e.extra) as extras 
from table_car c, table_car_extras_link l, table_extras e 
where c.car_id=l.car_id and l.extra_id=e.extra_id 
group by c.car_id; 

WM_CONCAT就像字符串的SUM。

查看this page的連接技術。

+4

+1:漂亮的鏈接,總結了所有可用的技術。您可能想要添加WM_CONCAT不受支持,但未記錄。在11gR2中,您將使用LISTAGG(此處記錄:http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/functions087.htm#SQLRF30030) – 2009-11-10 11:44:12

2

下面將在9i中工作及以上,它採用Tom Kyte's concatenation function

SELECT c.car_id, c.make, c.model, stragg(e.extra) 
    FROM table_car c 
    LEFT JOIN table_car_extras_link ce ON c.car_id = ce.car_id 
    LEFT JOIN table_extras e ON ce.extra_id = e.extra_id 
GROUP BY c.car_id, c.make, c.model