Mysql Distinct select with replace

时间:2013-09-24 16:13:22

标签: mysql sql

我有以下mySql select语句,它返回以下结果,并争取得到我所追求的结果。

 select `tvshow`.`idShow` AS `idShow`,`tvshow`.`c00` AS `ShowName`,
         if(count(distinct `episode`.`c12`),
         count(distinct `episode`.`c12`),0) AS `TotalSeasons`,
        if(count(`episode`.`c12`),count(`episode`.`c12`),0) AS `TotalEpisodeCount`
    from
        ((((`tvshow`
        left join `tvshowlinkpath` ON ((`tvshowlinkpath`.`idShow` = `tvshow`.`idShow`)))
        left join `path` ON ((`path`.`idPath` = `tvshowlinkpath`.`idPath`)))
        left join `episode` ON ((`episode`.`idShow` = `tvshow`.`idShow`)))
        left join `files` ON ((`files`.`idFile` = `episode`.`idFile`)))
    group by `tvshow`.`idShow`
    having (count(`episode`.`c12`) > 0)

选择结果

Select Result

我正试图获得第四列,其中列出了季节,例如“第1季,第2季,第3季”

我可以通过运行以下select

来获取所需的数据

select distinct c12 from episode where idShow = 1

返回以下内容。

enter image description here

所以我认为我可以使用替换来将结果更改为“Season1”但不知道如何让它只返回一个包含“Seasin1,Season2,Season3”的字符串,然后将其添加到选择语句中在视图的顶部并将它们组合在一起?

我想要的结果(使用Photoshop就可以了解这一点)

enter image description here

1 个答案:

答案 0 :(得分:1)

只需添加GROUP_CONCAT(episode.c12)作为附加列:

select `tvshow`.`idShow` AS `idShow`,`tvshow`.`c00` AS `ShowName`,
         if(count(distinct `episode`.`c12`),
         count(distinct `episode`.`c12`),0) AS `TotalSeasons`,
        if(count(`episode`.`c12`),count(`episode`.`c12`),0) AS `TotalEpisodeCount`,
        `GROUP_CONCAT(episode.c12)` as `Seasons`
    from
        ((((`tvshow`
        left join `tvshowlinkpath` ON ((`tvshowlinkpath`.`idShow` = `tvshow`.`idShow`)))
        left join `path` ON ((`path`.`idPath` = `tvshowlinkpath`.`idPath`)))
        left join `episode` ON ((`episode`.`idShow` = `tvshow`.`idShow`)))
        left join `files` ON ((`files`.`idFile` = `episode`.`idFile`)))
    group by `tvshow`.`idShow`
    having (count(`episode`.`c12`) > 0)

有关此MySQL特定功能的文档,请参阅http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat