2009-11-10 99 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