在sql join语句中合并两行

时间:2017-10-02 04:32:28

标签: sql sqlite

我的加入查询如下所示:

select distinct A.id as plan_id, A.start_date, A.end_date, C.title 
from cp_plan A left outer join cp_plan_zone_map B 
on A.id = B.plan_id left outer join cp_zone C 
on B.zone_id = C.id where A.status = 'in-planning'  

这给了我以下结果:

enter image description here

由于我的计划ID,开始日期和结束日期都相同,我想要的是合并这样的标题:

enter image description here

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

汇总plan_idstart_dateend_date,并使用GROUP_CONCAT生成以连字符分隔的标题列表:

SELECT
    A.id AS plan_id,
    A.start_date,
    A.end_date,
    GROUP_CONCAT(C.title, '-') AS title
FROM cp_plan A
LEFT JOIN cp_plan_zone_map B 
    ON A.id = B.plan_id
LEFT JOIN cp_zone C 
    ON B.zone_id = C.id
WHERE
    A.status = 'in-planning'
GROUP BY
    A.id,
    A.start_date,
    A.end_date;

答案 1 :(得分:0)

找到答案here

SELECT A.id AS plan_id,
       A.start_date,
       A.end_date,
       group_concat(C.title, '-') AS title
FROM cp_plan A
LEFT OUTER JOIN cp_plan_zone_map B ON A.id = B.plan_id
LEFT OUTER JOIN cp_zone C ON B.zone_id = C.id
WHERE A.status = 'in-planning'
GROUP BY plan_id