MySQL 如何将具有相同列值的mysql行分组为一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3664393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:05:59  来源:igfitidea点击:

How to group mysql rows with same column value into one row?

sqlmysqlaggregate-functions

提问by jarkam

I have two tables, keywords and data.

我有两个表,关键字和数据。

Table keywords have 2 columns (id, keyword), table data have 3 columns (id[foreign key of keywords.id], name, value).

表关键字有2列(id,关键字),表数据有3列(id[keywords.id的外键],名称,值)。

I am using this query:

我正在使用这个查询:

SELECT k.id, d.value, d.name
FROM keywords AS k
INNER JOIN data as d ON k.id = d.id

it returns something like:

它返回如下内容:

1 123 name1
1 456 name2
2 943 name1
3 542 name1
3 532 name2
3 682 name3

Each id can have values from 0 to 3 (maybe more in the future).

每个 id 的值可以从 0 到 3(将来可能会更多)。

How can I retrieve all the rows with the same id in the same row?

如何检索同一行中具有相同 id 的所有行?

Like

喜欢

1 123 456
2 943
3 542 532 682

I want to do this because I want to be able to sort the values.

我想这样做是因为我希望能够对值进行排序。

回答by shamittomar

Use GROUP_CONCAT()like this:

GROUP_CONCAT()像这样使用:

 SELECT k.id, GROUP_CONCAT(d.value)
  FROM keywords AS k
  INNER JOIN data as d ON k.id = d.id
  GROUP BY k.id

Also, you may need to do ORDER BY d.nameto get exact order of values as you want. Like this:

此外,您可能需要根据需要ORDER BY d.name获取确切的值顺序。像这样:

 SELECT k.id, GROUP_CONCAT(d.value ORDER BY d.name separator ' ')
  FROM keywords AS k
  INNER JOIN data as d ON k.id = d.id
  GROUP BY k.id