【问题标题】:Delete duplicated tags MySQL删除重复标签 MySQL
【发布时间】:2015-12-20 04:39:04
【问题描述】:

我的 MySQL 数据库中有重复的标签,如下所示:

| id  | tags                                |
+- ---+-------------------------------------+
| 3   | x,yz,z,x,x                          |
| 5   | a,b,c d,a,b,c d, d                  |
+-----+-------------------------------------+

如何执行可以删除重复标签的查询?

结果应该是:

| id  | tags                                |
+- ---+-------------------------------------+
| 3   | x,yz,z                              |
| 5   | a,b,c d, d                          |
+-----+-------------------------------------+

【问题讨论】:

  • 首先规范化你的数据
  • @amdixon 这不是一个选项,因为我无法更改架构。

标签: mysql tags


【解决方案1】:

设置

create table overly_complex_tags
(
  id integer primary key not null,
  tags varchar(100) not null
);

insert into overly_complex_tags
( id, tags )
values
( 3   , 'x,yz,z,x,x'           ),
( 5   , 'a,b,c d,a,b,c d,d'    )
;

create view digits_v
as
SELECT 0 AS N 
UNION ALL 
SELECT 1 
UNION ALL 
SELECT 2 
UNION ALL 
SELECT 3 
UNION ALL 
SELECT 4 
UNION ALL 
SELECT 5 
UNION ALL 
SELECT 6 
UNION ALL 
SELECT 7 
UNION ALL 
SELECT 8 
UNION ALL 
SELECT 9
;

查询删除重复标签

update overly_complex_tags t
inner join
(
select id, group_concat(tag) as new_tags
from
(
select distinct t.id, substring_index(substring_index(t.tags, ',', n.n), ',', -1) tag
from overly_complex_tags t 
cross join
(
  select a.N + b.N * 10 + 1 n
  from digits_v a
  cross join digits_v b
  order by n
) n
where n.n <= 1 + (length(t.tags) - length(replace(t.tags, ',', '')))
) cleaned_tags
group by id
) updated_tags
on t.id = updated_tags.id
set t.tags = updated_tags.new_tags
;

输出

+----+-----------+
| id |   tags    |
+----+-----------+
|  3 | yz,z,x    |
|  5 | c d,a,d,b |
+----+-----------+

sqlfiddle


注意

上述解决方案的复杂性来自于没有适当的 标准化结构.. 请注意,该解决方案使用中间 归一化结构

【讨论】:

  • 不知道什么更有趣。问题或这个:P
【解决方案2】:

在 Oracle 中,我们将其实现为

Update table set col=(select distinct regexp_substr(col, '[^,]+', 1, level) col
          from table)

但对于 MySQL,这是不可能的,唯一的方法是通过 PHP 数组,如 here 所述。然而 Maria db 也有它的解决方案。所以使用中间方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2012-12-29
    • 2014-09-15
    相关资源
    最近更新 更多