简体   繁体   中英

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.

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.

Basically the above are values for first name and last name. field_id is a foreign_key to a different table.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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