如果下一个值与当前值相同,如何从 MySQL 分组 concat 并且不重复相同的值

How to group concat from MySQL and not repeat the same value if next value is same as current value

我有一个这样的table(位置)

id | loc id
1  | Location A
2  | Location B
3  | Location B
4  | Location C
5  | Location A
6  | Location B
7  | Location B

我希望 MySQL 的结果像这样

Location A, Location B, Location C, Location A, Location B

但这就是我得到的

Location A, Location B, Location B, Location C, Location A, Location B, Location

如何实现?

对于 MySql 8.0+,您可以使用 window 函数 LAG() 过滤掉与前一行具有相同 locid 的行:

select group_concat(t.locid order by t.id) locations 
from (
  select *, lag(locid) over (order by id) prev
  from location
) t  
where t.locid <> t.prev or t.prev is null

对于以前的版本,如果 id 之间没有间隙,您可以使用 NOT EXISTS:

select group_concat(locid order by id) locations 
from location l
where not exists (select 1 from location where locid = l.locid and id = l.id - 1)

如果 id 之间存在间隙,则在 WHERE 子句中使用相关子查询来获取前一个 id:

locid 的值
select group_concat(locid order by id) locations 
from location l
where l.locid <> coalesce(
  (select locid from location where id < l.id order by id desc limit 1), 
  ''
)

参见demo
结果:

> | locations                                              |
> | :----------------------------------------------------- |
> | Location A,Location B,Location C,Location A,Location B |