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

使用MySQL,我可以这样做:

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

我的输出:

shoppingfishingcoding

但我只想要1排,1列:

预期产出:

shopping, fishing, coding

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

我在mysql文档上查找了一个函数,它看起来不像CONCATCONCAT_WS函数接受结果集。

这里有人知道怎么做吗?

840804 次浏览

您可以使用#0

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

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

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

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

SELECT person_id,GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')FROM peoples_hobbiesGROUP 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_hobbiesGROUP BY person_id) AS UNSIGNED);

有一个GROUP聚合函数,GROUP_CONCAT

如果您的MySQL版本(4.1)支持,请查看GROUP_CONCAT。有关更多详细信息,请参阅留档

它看起来像:

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

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

请参阅MySQL文档中的详细信息。

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

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

然后你可以得到

test1,test11

在我的例子中,我有一行id,有必要将其转换为char,否则,结果被编码为二进制格式:

SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table

连接多个单独的行的替代语法

警告:这篇文章会让你饿。

给定:

我发现自己想要选择多个单独的行-而不是一个组-并在某个领域连接。

假设您有一个产品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 |+------------+--------------------+-------+

然后你有一些花哨的schmancy ajax,列出这些小狗作为复选框。

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

查找:

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

解决方案:

GROUP_CONCAT#1条款一起使用:

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 |+------------------------------------------------+

奖励解决方案:

如果您也想要总价,请输入#0

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 |+------------------------------------------------+-------+

试试这个:

DECLARE @Hobbies NVARCHAR(200) = ' '
SELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;

太长别读;

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 dummyFROM INFORMATION_SCHEMA.COLUMNSWHEREINFORMATION_SCHEMA.COLUMNS.DATA_TYPE like '%char%'and INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA='xxx'and INFORMATION_SCHEMA.COLUMNS.TABLE_NAME='yyy';select @result;

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

原始查询:

SELECT DISTINCT userIDFROM event GROUP BY userIDHAVING count(distinct(cohort))=2);

内爆:

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

我希望这可以帮助某人。

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

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

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

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

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

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

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

查询:

SELECT pm.id, pm.name, GROUP_CONCAT(c.name) as channel_namesFROM payment_methods pmLEFT JOIN payment_methods_channels_pivot pmcp ON pmcp.payment_method_id = pm.idLEFT JOIN channels c ON c.id = pmcp.channel_idGROUP BY pm.id

表格

payment_methodsid  | name1   | PayPal
channelsid  | name1   | Google2   | Faceook
payment_methods_channels_pivotpayment_method_id | channel_id1                 |  11                 |  2

输出:

输入图片描述

在sql服务器中,使用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

另一个有趣的例子——

以下是示例表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()

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

Set @concatHobbies = '';SELECT TRIM(LEADING ', ' FROM T.hobbies ) FROM(selectId, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbiesfrom peoples_hobbies)TOrder by Id DESCLIMIT 1

这里

   selectId, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbiesfrom peoples_hobbies

将返回

  Id    hobbies1     , shopping2     , shopping, fishing3     , shopping, fishing, coding

现在我们的预期结果是在第三位。所以我用最后一行

  Order by Id DESCLIMIT 1  

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

 TRIM(LEADING ', ' FROM T.hobbies )

使用GROUP_CONCAT

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