Before diving into a Python script to do this for me, I am wondering if we can achieve this via a MySQL query alone?
I have a table with multiple records per ID. I want to concatenate the multiple values into one record and concatenate based on priority? Still with me?
A table might help :
ID Value Priority
1 AA 1
1 KK 3
1 CC 2
2 AA 1
3 EE 4
3 FF 5
2 HH 6
Desired Output :
ID Concat_Value
1 AA, CC, KK
2 AA, HH
3 EE, FF
Priority goes in an increasing order. Smaller the number, higher the priority.
Easy as pie.
SELECT id, GROUP_CONCAT(`value` ORDER BY priority) as concat_value
FROM table1
GROUP BY id
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
If you want a space in the group_concat, you'll have to change the separator:
SELECT
id
, GROUP_CONCAT(`value` ORDER BY priority SEPARATOR ', ') as concat_value
FROM table1
GROUP BY id
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.