我有一个表(章),其中包含5列,供组织中的高级职员使用:ID(key)、president、vice_president、secretary、fiscaler。每个办公室都有一个个人的参考号。
对于某些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。
任何帮助或指导将不胜感激!

最佳答案

一种方法使用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;

关于mysql - 连接MySQL中重复值的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38339163/

10-11 03:00
查看更多