Using GROUP_CONCAT on subquery in MySQL

前端 未结 5 1705
我在风中等你
我在风中等你 2021-02-02 06:28

I have a MySQL query in which I want to include a list of ID\'s from another table. On the website, people are able to add certain items, and people can then add those items to

5条回答
  •  一生所求
    2021-02-02 06:31

    Yes, soulmerge's solution is ok. But I needed a query where I had to collect data from more child tables, for example:

    • main table: sessions (presentation sessions) (uid, name, ..)
    • 1st child table: events with key session_id (uid, session_uid, date, time_start, time_end)
    • 2nd child table: accessories_needed (laptop, projector, microphones, etc.) with key session_id (uid, session_uid, accessory_name)
    • 3rd child table: session_presenters (presenter persons) with key session_id (uid, session_uid, presenter_name, address...)

    Every Session has more rows in child tables tables (more time schedules, more accessories)

    And I needed to collect in one collection for every session to display in ore row (some of them):

    session_id | session_name | date | time_start | time_end | accessories | presenters
    

    My solution (after many hours of experiments):

    SELECT sessions.uid, sessions.name,
        ,(SELECT GROUP_CONCAT( `events`.date SEPARATOR '
  • ') FROM `events` WHERE `events`.session_id = sessions.uid ORDER BY `events`.date) AS date ,(SELECT GROUP_CONCAT( `events`.time_start SEPARATOR '
  • ') FROM `events` WHERE `events`.session_id = sessions.uid ORDER BY `events`.date) AS time_start ,(SELECT GROUP_CONCAT( `events`.time_end SEPARATOR '
  • ') FROM `events` WHERE `events`.session_id = sessions.uid ORDER BY `events`.date) AS time_end ,(SELECT GROUP_CONCAT( accessories.name SEPARATOR '
  • ') FROM accessories WHERE accessories.session_id = sessions.uid ORDER BY accessories.name) AS accessories ,(SELECT GROUP_CONCAT( presenters.name SEPARATOR '
  • ') FROM presenters WHERE presenters.session_id = sessions.uid ORDER BY presenters.name) AS presenters FROM sessions

    So no JOIN or GROUP BY needed. Another useful thing to display data friendly (when "echoing" them):

    • you can wrap the events.date, time_start, time_end, etc in "
      • ...
      " so the "
    • " used as separator in the query will separate the results in list items.

    I hope this helps someone. Cheers!

提交回复
热议问题