您没有指定您使用的 RDBMS。在 MySQL 中,您可以使用GROUP_CONCAT()
:
select t1.pid,
t1.name,
group_concat(t3.address) Address
from table1 t1
left join table2 t2
on t1.pid = t2.pid
left join table3 t3
on t2.moid = t3.moid
group by t1.pid, t1.name
请参阅带有演示的 SQL Fiddle
编辑#1,如果你想要UPDATE
这个结果的表,那么UPDATE
语句将如下所示:
update table1 t1
set address = (SELECT group_concat(t3.address)
FROM table2 t2
left join table3 t3
on t2.moid = t3.moid
where t1.pid = t2.pid
group by t1.pid, t1.name);
请参阅带有演示的 SQL Fiddle
如果您使用的是 Oracle 11g+,那么您可以使用以下ListAgg()
功能:
select t1.pid,
t1.name,
listagg(t3.address, ', ') WITHIN GROUP (ORDER BY t1.pid) Address
from table1 t1
left join table2 t2
on t1.pid = t2.pid
left join table3 t3
on t2.moid = t3.moid
group by t1.pid, t1.name
请参阅带有演示的 SQL Fiddle
在 SQL Server 中,您可以使用FOR XML PATH
来获取结果:
select t1.pid,
t1.name,
STUFF((SELECT DISTINCT ', '+ t3.address
FROM table3 t3
LEFT JOIN table2 t2
ON t2.moid = t3.moid
WHERE t1.pid = t2.pid
FOR XML PATH('')), 1, 1, '') Address
from table1 t1
group by t1.pid, t1.name
请参阅带有演示的 SQL Fiddle
所有这些都会产生结果:
| PID | NAME | ADDRESS |
-------------------------------------------
| 1 | Dale | 12 South,99 North,123 Main |