如何将具有相同列值的mysql行分组为一行? [英] How to group mysql rows with same column value into one row?
本文介绍了如何将具有相同列值的mysql行分组为一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个表,关键字和数据.
I have two tables, keywords and data.
表关键字具有2列(id,关键字),表数据具有3列(id [keywords.id的外键,名称,值).
Table keywords have 2 columns (id, keyword), table data have 3 columns (id[foreign key of keywords.id], name, value).
我正在使用此查询:
SELECT k.id, d.value, d.name
FROM keywords AS k
INNER JOIN data as d ON k.id = d.id
它返回如下内容:
1 123 name1
1 456 name2
2 943 name1
3 542 name1
3 532 name2
3 682 name3
每个id的值可以为0到3(将来可能会更多).
Each id can have values from 0 to 3 (maybe more in the future).
如何在同一行中检索具有相同ID的所有行?
How can I retrieve all the rows with the same id in the same row?
喜欢
1 123 456
2 943
3 542 532 682
我想这样做是因为我希望能够对值进行排序.
I want to do this because I want to be able to sort the values.
推荐答案
Use GROUP_CONCAT()
like this:
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
此外,您可能需要执行ORDER BY d.name
来获取所需的确切值顺序.像这样:
Also, you may need to do ORDER BY d.name
to get exact order of values as you want. Like this:
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
这篇关于如何将具有相同列值的mysql行分组为一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文