首页 > 解决方案 > mysql无法在视图中显示重复的条目

问题描述

我在玛丽亚数据库中有下表

在此处输入图像描述

我正在寻找以下输出作为视图

在此处输入图像描述

我尝试了不同的方法,但它不起作用。

标签: mysqlmariadb

解决方案


用于group_concat()聚合 id 并对表进行自连接:

select t.id, t.name, 
  group_concat(tt.id order by tt.id) repeated
from tablename t left join tablename tt
on tt.name = t.name and tt.id <> t.id
group by t.id, t.name                             
order by t.id

请参阅演示
结果:

| id  | name  | repeated |
| --- | ----- | -------- |
| 1   | John  | 4,8      |
| 2   | Smith | 3        |
| 3   | Smith | 2        |
| 4   | John  | 1,8      |
| 5   | Anna  |          |
| 6   | David | 7        |
| 7   | David | 6        |
| 8   | John  | 1,4      |

推荐阅读