我有两个表:
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
感谢您的帮助。
最佳答案
您可以使用 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
关于MYSQL JOIN 2表并返回逗号分隔字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56567985/