MySQL - Split field and group concat

孤街醉人 提交于 2019-12-12 02:16:59

问题


I need to join two MySQL tables - events & people, but I see problem when I have multiple people leading the same event.

PEOPLE
=================
ID|Name  |Surname|....
--------------------
 1|John  |Lennon
 2|Paul  |McCartney 
 3|George|Harisson
 4|Ringo |Starr

Is there any possible way to get concat of 1 & 2, if the event table is something like

EVENTS
=================
event |leader|....
-----------------
Picnic|1+2

I do want some events to have only one leader, but also some with more than 2.

Is there any way to do something like this?

Thank you for your help.


回答1:


The proper way to solve your problem is to have a events table:

eventid | event
---------------
1       | Picnic

and a events_leaders table:

eventid | leader
----------------
1       | 1
1       | 2

then you can just use a JOIN and a GROUP_CONCAT aggregate function:

SELECT
  events.event,
  GROUP_CONCAT(CONCAT(people.surname, ' ', people.name))
FROM
  events INNER JOIN events_leaders
  ON events.eventid = events_leaders.eventid
  INNER JOIN people
  ON events_leaders.leader = people.id
GROUP BY
  events.eventid,
  events.event

however, you can use FIND_IN_SET function and obtain the same result, but the query will be slower as it works on strings and cannot make use of an index:

SELECT
  events.event,
  GROUP_CONCAT(CONCAT(people.surname, ' ', people.name))
FROM
  events INNER JOIN people
  ON FIND_IN_SET(people.id, REPLACE(events.leaders, '+', ','))>0
GROUP BY
  events.event


来源:https://stackoverflow.com/questions/25962738/mysql-split-field-and-group-concat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!