mysql GROUP_CONCAT 重复项

问题描述 投票:0回答:2

我从 farmTOanimal 表中进行加入,如下所示。有一个类似的farmTotool表

id | FarmID  | animal
 1 |    1    | cat
 2 |    1    | dog

当我在视图中加入表格时,我得到的结果如下

FarmID | animal | tool
   1   |  cat   | shovel
   1   |  dog   | shovel
   1   |  cat   | bucket
   1   |  dog   | bucket

现在,我执行 GROUP BY FarmID、GROUP_CONCAT(animal) 和 GROUP_CONCAT(tool),我明白了

FarmID |     animals     |         tools
  1    | cat,dog,cat,dog | shovel,shovel,bucket,bucket

但是,我真正想要的是看起来像这样的结果。我该怎么办?

FarmID | animals |    tools
  1    | cat,dog | shovel,bucket
sql mysql group-concat
2个回答
190
投票

您需要使用

DISTINCT
选项:

GROUP_CONCAT(DISTINCT animal)

0
投票

此外,如果您想更改默认分隔符

,
,请使用以下语法:

GROUP_CONCAT(DISTINCT animal || '\n')
© www.soinside.com 2019 - 2024. All rights reserved.