如何将具有相同列值的mysql行组合成一行?

时间:2021-12-08 09:12:03

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.

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

1 个解决方案

#1


65  

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.name to 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

#1


65  

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.name to 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