sql 在两个数据表中,A表存在字段以逗号分隔存储B表的多id对象,进行关联查询

A表
table

B表
table

关联查询

需求为,查询出A表的数据列表,需要将A表关联B表的数据id,概要通过B表的 name 进行输出显示

SELECT 
    A.id,
    A.name,
    A.creator,
    A.created_at,
    GROUP_CONCAT(B.name SEPARATOR ', ') AS B_names  -- 将 B表 name 合并为逗号分隔的字符串
FROM 
    xf_service_type A
LEFT JOIN apptype B 
    ON FIND_IN_SET(B.id, REPLACE(A.apptype_ids, ' ', ''))  -- 处理 apptype_ids 中的 id 列表
WHERE 
    A.is_del = 0 
GROUP BY 
    A.id, A.name, A.creator, A.created_at;  -- 按字段分组

结果:
table

posted @ 2025-03-17 15:58  二月雪  阅读(102)  评论(0)    收藏  举报