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

标签 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

感谢您的帮助。

最佳答案

您可以使用 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/

相关文章:

asp.net - asp mvc 从 savechanges() 获取最后一个插入 id

SQL 查找和引用表定义

sql - 在 SQL 中连接大表

php - Symfony2学说mysql IN查询

python - 是否有使用 Sqlalchemy 的 Flask 动态查询生成器?

mysqldump 在 perl 脚本中抛出错误,但在脚本之外运行良好

python - 如何从他的 ManyToMany 关系中选择包含某些 child 的 parent ?

java - prepareStatement.executeUpdate(sql) 给出错误

mysql - 动态href更改来自mysql的源

php - 对 php 中的 mysql 事务感到困惑