简体   繁体   English

mysql concat列基于一列的两行

[英]mysql concat column from two rows based on a column

Have the following table which i am trying to concat two rows from the 'value' column into one 有下表,我正在尝试将“值”列中的两行合并为一个

mysql> select * from table;
+-----+---------+----------+------------------------+
| id  | rsvp_id | field_id | value                  |
+-----+---------+----------+------------------------+
| 181 |      37 |        1 | First                  |
| 184 |      37 |        4 | Last                   |
| 187 |      37 |       10 |                        |
| 190 |      37 |       13 | spicegirls             |
| 193 |      37 |        7 | mark@test2.com         |
| 196 |      40 |        1 | Brian                  |
| 199 |      40 |        1 | Smith                  |
| 202 |      40 |        7 | Brian@test .com        |
| 205 |      40 |       10 | BBQ                    |
+-----+---------+----------+------------------------+
9 rows in set (0.00 sec)

Ideally i'd like to get the following result 理想情况下,我想得到以下结果

rsvp_id  | value
========  ========
37         First Last
40         Brian Smith

The query only grabs the rows with field_id=1 then concats the value column and creates a new row with rsvp_id and the concat value. 该查询仅获取field_id = 1的行,然后连接值列,并使用rsvp_id和concat值创建一个新行。

Also, the field_id column right now and the 1 is an example, i'll have to figure out how to make it work so instead of 1 it takes the condition from a different table. 另外,现在的field_id列为1,这是一个示例,我将不得不弄清楚如何使其工作,因此,它取而代之的是从另一个表中获取条件而不是1

Basically the above are values for first name and last name. 以上基本上是名字和姓氏的值。 field_id is a foreign_key to a different table. field_id是另一个表的外键。

I've tried searching online and messing with it myself but i wasn't able to merge the two rows into one row. 我曾尝试过在线搜索并自己弄乱它,但无法将两行合并为一行。

Thank You. 谢谢。

You have to use grouping and then use GROUP_CONCAT . 您必须使用分组,然后使用GROUP_CONCAT

Something like this (untested) might work: 像这样(未经测试)可能会起作用:

   SELECT rsvp_id, GROUP_CONCAT(value SEPARATOR ' ')
     FROM t
    WHERE field_id = 1
 GROUP BY rsvp_id

See MySQL docs for details, also to learn about ordering of values etc: https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat 有关详细信息,请参见MySQL文档,还可以了解值的排序等: https : //dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM