sql内连接单表

时间:2016-01-25 19:35:20

标签: sql

三栏表; ID,术语,同义词

1, IDENTITY, CHARACTER
2, IDENTITY, EXISTENCE
3, IDENTITY, IDENTIFICATION
4, IDENTITY, INTEGRITY 
5, IDENTITY, NAME
6, CIRCUMSTANCES, ASSETS
7, CIRCUMSTANCES, CAPITAL
8, CIRCUMSTANCES, CHANCES

我需要结果才能返回不同的" term"与关联的"同义词"消除多对多,并将结果带回一对多。

1, IDENTITY, CHARACTER | EXISTENCE | IDENTIFICATION | INTEGRITY | NAME
6, CIRCUMSTANCES, ASSETS |CAPITAL | CHANCES

或者,

1,TERM =" IDENTITY" SYNONYM =" CHARACTER" SYNONYM ="存在性" SYNONYM ="鉴定" SYNONYM =" INTEGRITY" SYNONYM =" NAME"

2,TERM =" CIRCUMSTANCES" SYNONYM ="资产" SYNONYM =" CAPITAL" SYNONYM =" CHANCES"

2 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL,则可以使用GROUP_CONCAT

SELECT MIN(`ID`), `TERM`, GROUP_CONCAT(`SYNONYM`, ' | ') 
FROM my_table
GROUP BY `TERM`;

答案 1 :(得分:0)

Oracle解决方案 - 自11g开始:

with sample as
(
  select 1 ID,  'IDENTITY' term , 'CHARACTER' syn from dual
  union all
  select 2, 'IDENTITY', 'EXISTENCE' from dual 
  union all
  select 3, 'IDENTITY', 'IDENTIFICATION' from dual 
  union all
  select 4, 'IDENTITY', 'INTEGRITY' from dual 
  union all
  select 5, 'IDENTITY', 'NAME' from dual 
  union all
  select 6, 'CIRCUMSTANCES', 'ASSETS' from dual 
  union all
  select 7, 'CIRCUMSTANCES', 'CAPITAL' from dual 
  union all
  select 8, 'CIRCUMSTANCES', 'CHANCES' from dual 
)
select  min(id) id, term,
listagg(syn,'|') within group(order by syn) syns
from sample
group by term;

输出:

      ID TERM          SYNS
---------- ------------- ------------------------------------------------------
         6 CIRCUMSTANCES ASSETS|CAPITAL|CHANCES
         1 IDENTITY      CHARACTER|EXISTENCE|IDENTIFICATION|INTEGRITY|NAME