我可以将多个MySQL行连接成一个字段吗?

Can I concatenate multiple MySQL rows into one field?

提问人:Dean Rather 提问时间:11/10/2008 最后编辑:Arsen KhachaturyanDean Rather 更新时间:3/18/2023 访问量:888967

问:

使用 ,我可以做如下事情:MySQL

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

我的输出:

shopping
fishing
coding

但相反,我只想要 1 行,1 列:

预期输出:

shopping, fishing, coding

原因是我从多个表中选择了多个值,并且在所有联接之后,我的行数比我想要的要多得多。

我在 MySQL Doc 上寻找了一个函数,它看起来不像 or 函数接受结果集。CONCATCONCAT_WS

那么这里有人知道如何做到这一点吗?

MySQL SQL 串联 组-concat

评论

10赞 Marc Giombetti 6/7/2013
我刚刚写了一个关于如何使用group_concat的小演示,这可能对你有用:giombetti.com/2013/06/06/mysql-group_concat
0赞 Aasif khan 1/13/2021
这可能有助于您 w3resource.com/mysql/aggregate-functions-and-grouping/...
0赞 Golden Lion 8/14/2021
可以使用 XPath 在列中透视行

答:

2085赞 14 revs, 12 users 16%Ankit Jindal #1

您可以使用GROUP_CONCAT

SELECT person_id,
   GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

正如 Ludwig 在他的评论中所说,您可以添加运算符以避免重复:DISTINCT

SELECT person_id,
   GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

正如 Jan 在他们的评论中所说,您还可以在内爆之前使用以下方法对值进行排序:ORDER BY

SELECT person_id, 
       GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

正如 Dag 在他的评论中所说,结果有 1024 字节的限制。若要解决此问题,请在查询之前运行此查询:

SET group_concat_max_len = 2048;

当然,您可以根据需要进行更改。要计算和赋值,请执行以下操作:2048

SET group_concat_max_len = CAST(
                     (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
                           FROM peoples_hobbies
                           GROUP BY person_id) AS UNSIGNED);

评论

175赞 Dag 3/28/2012
请注意结果列中 1024 个字节的限制(请参阅参数 group_concat_max_len)
87赞 Ludwig 6/18/2012
并添加参数,您将不会获得任何双精度。DISTINCT... GROUP_CONCAT(DISTINCT hobbies)
0赞 Bikash Gyawali 1/25/2023
即使省略了末尾的子句,我也得到了相同的结果。GROUP BY person_id
31赞 Dean Rather 11/10/2008 #2

GROUP_CONCAT,有一个 GROUP Aggregate 函数。

126赞 lpfavreau 11/10/2008 #3

看看你的MySQL版本(4.1)是否支持它。有关更多详细信息,请参阅文档GROUP_CONCAT

它看起来像这样:

  SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') 
  FROM peoples_hobbies 
  WHERE person_id = 5 
  GROUP BY 'all';

评论

15赞 Krzysiek 10/20/2014
我认为这不是必需的(而且是不需要的),因为这会分配给所有行字符串,然后比较这些行之间的字符串。我说得对吗?group by 'all'all
41赞 pau.moreno 4/8/2010 #4

您可以通过设置参数来更改值的最大长度。GROUP_CONCATgroup_concat_max_len

有关详细信息,请参阅 MySQL 文档

19赞 Shen liang 9/28/2013 #5

使用 MySQL(5.6.13) 会话变量和赋值运算符,如下所示

SELECT @logmsg := CONCAT_ws(',',@logmsg,items) FROM temp_SplitFields a;

然后你可以得到

test1,test11

评论

2赞 jave.web 2/7/2014
它比GROUP_CONCAT快吗?
2赞 Jan 3/8/2017
我在 PHPMyAdmin 下使用 MySQL 服务器 v5.6.17 对测试表中的描述列 (varchar(50)) 进行了测试,但它为每条记录返回一个 BLOB 字段:SELECT @logmsg := CONCAT_ws(',',@logmsg,description) from test
28赞 Fedir RYKHTIK 6/10/2014 #6

就我而言,我有一行 Id,必须将其转换为 char,否则,结果被编码为二进制格式:

SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table
93赞 elbowlobstercowstand 9/24/2014 #7

我发现自己想要选择多个单独的行(而不是一组),并在某个字段上连接。

鉴于:

假设您有一个产品 ID 及其名称和价格表:

+------------+--------------------+-------+
| product_id | name               | price |
+------------+--------------------+-------+
|         13 | Double Double      |     5 |
|         14 | Neapolitan Shake   |     2 |
|         15 | Animal Style Fries |     3 |
|         16 | Root Beer          |     2 |
|         17 | Lame T-Shirt       |    15 |
+------------+--------------------+-------+

然后你有一些花哨的 ajax 将这些小狗列为复选框。

饥饿的河马用户选择 。今天没有给她吃甜点......13, 15, 16

找到:

一种用纯 mysql 在一行中总结用户订单的方法。

溶液:

IN 子句一起使用:GROUP_CONCAT

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);

输出:

+------------------------------------------------+
| order_summary                                  |
+------------------------------------------------+
| Double Double + Animal Style Fries + Root Beer |
+------------------------------------------------+

奖金解决方案:

如果你也想要总价,请抛入 SUM()

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);
+------------------------------------------------+-------+
| order_summary                                  | total |
+------------------------------------------------+-------+
| Double Double + Animal Style Fries + Root Beer |    10 |
+------------------------------------------------+-------+

评论

18赞 THC 11/16/2016
尽管这是一个很好的答案,但这听起来更像是广告,而不是纯粹的回答。仍然是一个很好的格式良好的答案。
0赞 Payel Senapati 10/4/2021
这与OP的问题有什么关系?
10赞 thejustv 2/26/2015 #8

试试这个:

DECLARE @Hobbies NVARCHAR(200) = ' '

SELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;

TL;博士;

set @sql='';
set @result='';
set @separator=' union \r\n';
SELECT 
@sql:=concat('select ''',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME  ,''' as col_name,',
INFORMATION_SCHEMA.COLUMNS.CHARACTER_MAXIMUM_LENGTH ,' as def_len ,' ,
'MAX(CHAR_LENGTH(',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME , '))as  max_char_len',
' FROM ',
INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
) as sql_piece, if(@result:=if(@result='',@sql,concat(@result,@separator,@sql)),'','') as dummy
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE 
INFORMATION_SCHEMA.COLUMNS.DATA_TYPE like '%char%'
and INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA='xxx' 
and INFORMATION_SCHEMA.COLUMNS.TABLE_NAME='yyy';
select @result;

评论

2赞 Istiaque Ahmed 11/8/2017
这是我得到的:'无法识别的语句类型。(位置 0 处的“DECLARE”附近)'
20赞 Alex Bowyer 4/30/2015 #9

我有一个更复杂的查询,发现我必须在外部查询中使用才能使其工作:GROUP_CONCAT

原始查询:

SELECT DISTINCT userID 
FROM event GROUP BY userID 
HAVING count(distinct(cohort))=2);

内爆:

SELECT GROUP_CONCAT(sub.userID SEPARATOR ', ') 
FROM (SELECT DISTINCT userID FROM event 
GROUP BY userID HAVING count(distinct(cohort))=2) as sub;

希望这可能会对某人有所帮助。

2赞 raghavendra 11/13/2018 #10

我们有两种方法可以在 MySql 中连接列

select concat(hobbies) as `Hobbies` from people_hobbies where 1

select group_concat(hobbies) as `Hobbies` from people_hobbies where 1
14赞 Oleg Abrazhaev 4/26/2019 #11

对于在这里寻找如何使用子查询的人 - 发布此示例GROUP_CONCAT

SELECT i.*,
(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist
FROM items i
WHERE i.id = $someid

所以必须在子查询中使用,而不是包装它。GROUP_CONCAT

2赞 Muhammad Shahzad 7/13/2021 #12

虽然很晚,但对于那些正在搜索“使用数据透视表将多个MySQL行连接成一个字段”的人来说会有所帮助:)

查询:

SELECT pm.id, pm.name, GROUP_CONCAT(c.name) as channel_names
FROM payment_methods pm
LEFT JOIN payment_methods_channels_pivot pmcp ON pmcp.payment_method_id = pm.id
LEFT JOIN channels c ON c.id = pmcp.channel_id
GROUP BY pm.id

payment_methods 
  id  | name
  1   | PayPal

channels
  id  | name
  1   | Google
  2   | Faceook

payment_methods_channels_pivot
   payment_method_id | channel_id
   1                 |  1
   1                 |  2

输出:

enter image description here

评论

1赞 Mohamed Raza 6/21/2022
GROUP_CONCAT(c.name)将多行连接成一列的工作原理
0赞 Golden Lion 8/14/2021 #13

在 SQL Server 中,使用 string_agg 将行字段值透视到列中:

select string_agg(field1, ', ') a FROM mytable 

or

select string_agg(field1, ', ') within group (order by field1 dsc) a FROM mytable group by field2
1赞 Payel Senapati 10/4/2021 #14

在这种情况下,另一个有趣的例子——

以下是示例表的结构people_hobbies -

DESCRIBE people_hobbies;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int unsigned | NO   | PRI | NULL    | auto_increment |
| ppl_id  | int unsigned | YES  | MUL | NULL    |                |
| name    | varchar(200) | YES  |     | NULL    |                |
| hby_id  | int unsigned | YES  | MUL | NULL    |                |
| hobbies | varchar(50)  | YES  |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+

该表的填充方式如下:

SELECT * FROM people_hobbies;
+----+--------+-----------------+--------+-----------+
| id | ppl_id | name            | hby_id | hobbies   |
+----+--------+-----------------+--------+-----------+
|  1 |      1 | Shriya Jain     |      1 | reading   |
|  2 |      4 | Shirley Setia   |      4 | coding    |
|  3 |      2 | Varsha Tripathi |      7 | gardening |
|  4 |      3 | Diya Ghosh      |      2 | fishing   |
|  5 |      4 | Shirley Setia   |      3 | gaming    |
|  6 |      1 | Shriya Jain     |      6 | cycling   |
|  7 |      2 | Varsha Tripathi |      1 | reading   |
|  8 |      3 | Diya Ghosh      |      5 | shopping  |
|  9 |      3 | Diya Ghosh      |      4 | coding    |
| 10 |      4 | Shirley Setia   |      1 | reading   |
| 11 |      1 | Shriya Jain     |      4 | coding    |
| 12 |      1 | Shriya Jain     |      3 | gaming    |
| 13 |      4 | Shirley Setia   |      2 | fishing   |
| 14 |      4 | Shirley Setia   |      7 | gardening |
| 15 |      2 | Varsha Tripathi |      3 | gaming    |
| 16 |      2 | Varsha Tripathi |      2 | fishing   |
| 17 |      1 | Shriya Jain     |      5 | shopping  |
| 18 |      1 | Shriya Jain     |      7 | gardening |
| 19 |      3 | Diya Ghosh      |      1 | reading   |
| 20 |      4 | Shirley Setia   |      5 | shopping  |
+----+--------+-----------------+--------+-----------+

现在,生成一个表格,其中包含所有人的列表和每个人的爱好列表,每个爱好都在一个新行中 -hobby_list

CREATE TABLE hobby_list AS
    -> SELECT ppl_id, name,
    -> GROUP_CONCAT(hobbies ORDER BY hby_id SEPARATOR "\n")
    -> AS hobbies
    -> FROM people_hobbies
    -> GROUP BY ppl_id
    -> ORDER BY ppl_id;
SELECT * FROM hobby_list;

CONCAT_GROUP()

2赞 Md. Tarikul Islam Soikot 11/9/2021 #15

在这里,我的意图是在不使用 group_concat() 函数的情况下应用字符串连接:

Set @concatHobbies = '';
SELECT TRIM(LEADING ', ' FROM T.hobbies ) FROM 
(
   select 
   Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies
   from peoples_hobbies
)T
Order by Id DESC
LIMIT 1

这里

   select 
   Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies
   from peoples_hobbies

会回来

  Id    hobbies
  1     , shopping
  2     , shopping, fishing
  3     , shopping, fishing, coding

现在我们的预期成绩是排在第三位。所以我使用

  Order by Id DESC 
  LIMIT 1
  

然后我也从我的字符串中删除了第一个','

 TRIM(LEADING ', ' FROM T.hobbies )
1赞 Haddock-san 7/8/2022 #16

使用GROUP_CONCAT

SELECT GROUP_CONCAT(hobbies) FROM peoples_hobbies WHERE person_id = 5;