我有一个表(章节),其中包含一个组织官员的5列:ID(密钥),总裁,副总裁,秘书,财务主管。每个办公室都有一个个人参考号的值。
对于某些ID,4个办事处中的多个办事处列出的值相同。您可以在下面看到我的数据结构的基本示例:
ID president vice_president secretary treasurer
105 1051456 1051456 1051466 1051460
106 1060923 1060937 1060944 1060944
108 1081030 1081027 1081032 1081017
110 1100498 1100491 1100485 1100485
我也在http://sqlfiddle.com/#!9/57df1
发布了相同内容我的目标是确定一个值何时在多个字段中,并选择该值以及找到它的所有列标题的连接列表。例如,从提供的样本数据集中,我最好返回以下内容:
member offices
1051456 president, vice_president
1060944 secretary, treasurer
1100485 secretary, treasurer
我发现了一些类似的其他例子,但似乎没有什么能用于我想做的事情。我是一个新手,但可以很好地将事情拼凑起来。我也在想通过加入information_schema数据库可能有一种更简单的方法,因为这是我过去提取列标题的方式。这似乎不应该像现在这样困难,希望我错过了一个简单而明显的解决方案。我的完整数据集相当大,我宁愿为了性能而避免任何密集的子查询。我的SQL格式是MySQL 5.5。
非常感谢任何帮助或指导!
答案 0 :(得分:1)
一种方法使用union all
取消数据的重新分配,然后重新聚合:
select member, group_concat(office)
from ((select id, president as member, 'president' as office from t) union all
(select id, vice_president, 'vice_president' as office from t) union all
(select id, secretary, 'secretary' as office from t) union all
(select id, treasurer, 'treasurer' as office from t)
) t
group by member
having count(distinct office) > 1;
如果要控制值的顺序,请添加优先级:
select member, group_concat(office order by priority) as offices
from ((select id, president as member, 'president' as office, 1 as priority from t) union all
(select id, vice_president, 'vice_president' as office, 2 from t) union all
(select id, secretary, 'secretary' as office, 3 from t) union all
(select id, treasurer, 'treasurer' as office, 4 from t)
) t
group by member
having count(distinct office) > 1;