【问题标题】:PHP MySQL consolidate column where other column has duplicatesPHP MySQL合并其他列重复的列
【发布时间】:2017-03-10 03:57:43
【问题描述】:

我有一个 MySQL 表,它有三列,第一列是唯一键 (INT(11) AUTO_INCREMENT),接下来是索引值 (VARCHAR(255)),第三列是描述 (TEXT)。第二列有重复值,但每一行都有不同的描述。我想删除第二列重复的所有行,但将相同索引值的每个描述附加到第一个实例的值,并用分号和空格分隔字符串。

例如,我的表是这样的:

cid   | word    | description
------------------------------
1     | cat     | an animal with wiskers
2     | cat     | a house pet
3     | dog     | a member of the canine family
4     | cat     | a cool person

我想把表格改成这样:

cid   | word    | description
------------------------------
1     | cat     | an animal with wiskers; a house pet; a cool person
3     | dog     | a member of the canine family

我不反对使用 PHP 脚本来执行此操作,但我更喜欢 MySQL。该表有超过 170,000 行,PHP 需要很长时间才能遍历它。

【问题讨论】:

  • MySQL 5.7 会在此处抱怨cid,因为您选择该数字的方式没有逻辑。它是最低的cid 值吗?可以在您的备用视图中省略该列吗?

标签: php mysql unique


【解决方案1】:

SQL:

select `cid`,`word`,group_concat(`description` SEPARATOR '; ') as `description` from `test_table` group by `word`;

好的..您可以将所有数据复制到另一个表中,然后重命名..

insert into `test_new` (`cid`,`word`,`desc`) (select `cid`,`word`,group_concat(`desc` SEPARATOR '; ') as `description` from `test_table` group by `word`);

mysql> describe `test_new`;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| word  | char(10) | YES  |     | NULL    |       |
| desc  | text     | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from `test_new`;
+------+------+---------------------+
| id   | word | desc                |
+------+------+---------------------+
|    1 | cat  | desc1; desc2; desc4 |
|    3 | dog  | desc3               |
+------+------+---------------------+
2 rows in set (0.00 sec)

【讨论】:

  • 在使用了那个 SQL 代码之后,你如何用选中的信息创建另一个表?
【解决方案2】:

如前所述,您可以创建一个新表并复制信息,也可以分两步完成,但前提是修改旧表没有问题:

UPDATE tableOld AS N1, tableOld AS N2 
SET N1.description = concat(concat(N1.description,"; "),N2.decription))
WHERE N2.word = N1.word

insert into tableNew (cid,name,description)select * from tableOld group by word

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2018-09-03
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多