代码之家  ›  专栏  ›  技术社区  ›  Dipak

组\u CONCAT和join,如何包含不匹配的行也

  •  1
  • Dipak  · 技术社区  · 7 年前

    如何在中包含不匹配的行 GROUP_CONCAT cls_sec

    等级 一个 部分 '和' ',

    等级 1节 ' '

    部分。

    这里的部分是连接表之间关系的关键,但如何包含 三班 组\u CONCAT

    cls

    id  |   ttl
    ===========
    1   |   One
    2   |   Two
    3   |   Three
    

    sec

    id  |   ttl
    ===========
    1   |   A
    2   |   B
    

    cls\秒 -分配给班级的每个部分的列表

    id  |   c_id|   s_id    
    =====================
    1   |   1   |   1
    2   |   1   |   2
    3   |   2   |   1
    

    ,我的期望如下:,

    1.One-B,1.One-A,2.Two-A,3.Three 
    

    其他的 仅回显类(如果任何节尚未分配给该类):

    MySQL代码

    SELECT
        GROUP_CONCAT(DISTINCT cls.id,'.',cls.en_ttl, '-', sec.en_ttl 
                     ORDER BY cls.id) AS cls
    FROM
        cls
    LEFT JOIN
        cls_sec ON cls_sec.c_id = cls.id
    JOIN
        sec ON sec.id = cls_sec.s_id OR cls_sec.s_id is NULL 
    ORDER BY cls.id DESC
    

    但我越来越

    1.One-B,1.One-A,2.Two-A,3.Three-B,3.Three-A
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Madhur Bhaiya    7 年前
    • Join OR .. IS NULL 条件需要替换为 LEFT JOIN .
    • 没有必要 ORDER BY
    • 使用 Coalesce()
    • 我补充说 Concat() 内部函数 Group_concat() ,以便于理解。然而,作为 suggested by @雷蒙德·尼兰德
    • Concat() null ,如果要连接的任何子字符串 无效的 - 进入之内 Concat() ,以避免任何拖尾 -

    尝试:

    SELECT
        GROUP_CONCAT(CONCAT(cls.id,'.',cls.en_ttl, 
                            COALESCE(CONCAT('-',sec.en_ttl), ''))  
                     ORDER BY cls.id) AS cls
    FROM
        cls
    LEFT JOIN
        cls_sec ON cls_sec.c_id = cls.id
    LEFT JOIN
        sec ON sec.id = cls_sec.s_id