如果你的Oracle 11g第2版,您可以使用LISTAGG
功能: http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm#SQLRF30030
select r.id, r.text, r.url
, listagg(k.keyword, ',') within group (order by k.keyword) as keywords
from results r
left join keyword_result kr on r.id = kr.result_id
left join keywords k on k.id = kr.keyword_id
group by r.id, r.text, r.url
order by r.id;
如果你有一個較低的Oracle版本,你必須定義自己的函數生成的逗號分隔列表,如下所示: Is there any function in oracle similar to group_concat in mysql? (請參閱get_comma_separated_value函數)。它應該是這樣的:
CREATE OR REPLACE FUNCTION get_comma_separated_value (input_val in number)
RETURN VARCHAR2
IS
return_text VARCHAR2(10000) := NULL;
BEGIN
FOR x IN (SELECT k.keyword FROM keyword_result kr
join keywords k on kr.keyword_id = k.id
WHERE kr.result_id = input_val) LOOP
return_text := return_text || ',' || x.keyword ;
END LOOP;
RETURN LTRIM(return_text, ',');
END;
/
那麼查詢將如下所示:
select r.id, r.text, r.url
, get_comma_separated_value(r.id) as keywords
from results r
left join keyword_result kr on r.id = kr.result_id
left join keywords k on k.id = kr.keyword_id
group by r.id, r.text, r.url
order by r.id;
你有什麼版本的Oracle? –