MYSQL JOIN 2表并返回逗号分隔的字段

时间:2019-06-12 18:02:15

标签: mysql sql

我有两个表:

appointments_recurring_forever

id | text
 1 | some text here 
 2 | other text
 3 | third appt text

recurring_appointments_exclude_dates

id | appt_id | date
 1 | 1       | 2019-01-01
 1 | 1       | 2019-05-21
 2 | 2       | 2020-11-05

我想根据约会ID将这两个表连接起来,但是我的预期结果需要像这样:

appt_id | text           | excluded_dates
 1      | some text here | 2019-01-01, 2019-05-21
 2      | other text     | 2020-11-05
 3      | third text     | null

我知道如何创建联接,但是如何创建一个以appt_id为基础的联接,同时创建以逗号分隔的排除日期的串联行?这是我到目前为止可以做的...

SELECT appts.id AS appt_id, appts.text 
FROM appointments_recurring_forever appts
LEFT JOIN recurring_appointments_exclude_dates ex_date ON ex_date.appt_id = 
appts.id

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用group_concat和group by

SELECT appts.id AS appt_id, appts.text, group_concat(date ) excluded_dates
FROM appointments_recurring_forever appts
LEFT JOIN recurring_appointments_exclude_dates ex_date ON ex_date.appt_id = appts.id
group by  appts.id AS appt_id, appts.text