根据第三个表中的字段将表中的多个记录合并到另一个表中的一个字段中

时间:2013-01-12 02:50:04

标签: sql

我有三张桌子:

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中的信息相关联?

2 个答案:

答案 0 :(得分: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,因为字符串连接在那里更难。

答案 1 :(得分: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 with Demo

编辑#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 with Demo

<击> 如果您使用的是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 with Demo

在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 with Demo

所有这些都产生了结果:

| PID | NAME |                    ADDRESS |
-------------------------------------------
|   1 | Dale | 12 South,99 North,123 Main |