-1

我有三张桌子:

Table 1: 
pid, name, address  
1    Dale  BLANK

Table 2: 
pid, moid  
1    12

Table 3: 
moid, address  
12    123 Main   
12    12 South   
12    99 North   

对于输出我需要:

Table 1: 
pid, name, address   
1    Dawn  123 Mian,12 South,99 North

如何将表 3 中的多个地址组合成表 1 中的一个地址字段,将两个表与表 2 中的信息链接起来?

4

2 回答 2

1

您可以通过连接执行此操作:

select table1.pid, table1.name,
       group_concat(table3.address, ', ')
from table2 join
     table1
     on table2.pid = table1.pid join
     table3
     on table2.moid = table3.moid
gorup by table1.pid

该函数group_concat并非在所有数据库中都存在。. . 其他字符串聚合函数是listaggws_concat。希望您没有使用 SQL Server,因为那里的字符串连接更难。

于 2013-01-12T02:57:53.917 回答
1

您没有指定您使用的 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 |
于 2013-01-12T02:59:56.847 回答