我有两个表,客户和产品。
产品:
productid name
1 pro1
2 pro2
3 pro3
客户:
id name productid
1 cust1 1,2
2 cust2 1,3
3 cust3
我要在select语句中关注结果,
id name productid
1 cust1 pro1,pro2
2 cust2 pro1,pro3
3 cust3
我在两个表中都有300多个记录,我是初学者到后端编码,有帮助吗?
答案 0 :(得分:2)
绝对不好的数据库设计,但坏的是您必须忍受这一点。这是我使用递归查询创建的解决方案。我看不到product
表的使用,因为您的要求与product
表无关。
with
--Expanding each row seperated by comma
tab(col1,col2,col3) as (
Select distinct c.id,c.prdname,regexp_substr(c.productid,'[^,]',1,level)
from customers c
connect by regexp_substr(c.productid,'[^,]',1,level) is not null
order by 1),
--Appending `Pro` to each value
tab_final as ( Select col1,col2, case when col3 is not null
then 'pro'||col3
else col3
end col3
from tab )
--Displaying result as expected
SELECT
col1,
col2,
LISTAGG(col3,',') WITHIN GROUP( ORDER BY col1,col2 ) col3
FROM
tab_final
GROUP BY
col1,
col2
演示:
--Preparing dataset
With
customers(id,prdname,productid) as ( Select 1, 'cust1', '1,2' from dual
UNION ALL
Select 2, 'cust2','1,3' from dual
UNION ALL
Select 3, 'cust3','' from dual),
--Expanding each row seperated by comma
tab(col1,col2,col3) as (
Select distinct c.id,c.prdname,regexp_substr(c.productid,'[^,]',1,level)
from customers c
connect by regexp_substr(c.productid,'[^,]',1,level) is not null
order by 1),
--Appending `Pro` to each value
tab_final as ( Select col1,col2, case when col3 is not null
then 'pro'||col3
else col3
end col3
from tab )
--Displaying result as expected
SELECT
col1,
col2,
LISTAGG(col3,',') WITHIN GROUP( ORDER BY col1,col2 ) col3
FROM
tab_final
GROUP BY
col1,
col2
PS:在使用时,请不要忘记将实际的表列放在我的示例中,这可能会有所不同。