简体   繁体   English

在 MySQL 查询中对逗号分隔的元素进行分组

[英]Group comma separated elements in MySQL query

It's kinda stupid question and I already made it work using php,but I was wondering can I group all the unique elements in a column separated by comma within my query call.这是一个有点愚蠢的问题,我已经使用 php 使它工作了,但我想知道我是否可以在查询调用中将所有唯一元素分组在以逗号分隔的列中。

I have a column with comma separated tags我有一列用逗号分隔的标签

  • tag1 , tag2 tag1 , tag2
  • tag2 , tag3 tag2tag3
  • tag3 , tag1 tag3 , tag3 tag1

currently I am making my query with GROUP BY ('tag_col') which returns as it is (like the list up there).目前我正在使用GROUP BY ('tag_col')进行查询,它按GROUP BY ('tag_col')返回(就像上面的列表一样)。 In the end I have to output a loop with all the unique tags, which I've done within my php script.最后,我必须输出一个包含所有唯一标签的循环,这是我在 php 脚本中完成的。 The question had to begin that by using group by it groups as separate rows that contain for example:问题必须通过使用 group by it 组作为单独的行开始,例如包含:

  • tag1 , tag2 tag1 , tag2

    and

  • tag2 , tag1 tag2 , tag1

Ain't there smarter way to list them all as tag1 , tag2 etc. before sorting it with php.在用 php 排序之前,没有更聪明的方法将它们全部列为tag1tag2等。

You can use GROUP_CONCAT for this i guess, it will allow you to concatenate all of them in one row by using GROUP_CONCAT(tag_col) and removing your group by.我猜您可以为此使用GROUP_CONCAT ,它将允许您通过使用GROUP_CONCAT(tag_col)并删除您的组来将所有这些连接在一行中。

Then with php you can turn it into an array and from there it's easy to remove any duplicates.然后使用 php 你可以把它变成一个数组,从那里很容易删除任何重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM