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

MySQL希望所有结果都来自左表,并且只过滤带有条件的右表

  •  0
  • arun  · 技术社区  · 8 年前

    让我们假设我有票桌:

    t_id,评论

    select
                    T.t_id as 'TicektID',
                    TK.tk_category as 'Category',
                    ifnull(T.contact_person,'N/A') as 'Contact_Person',
                    T.comment as 'Employee Comment',
                    COUNT(TD.t_detail_id) as 'User Comment',
                    T.t_status
                    from sun_it_tickets T
                    LEFT JOIN (
                    SELECT * from sun_it_ticket_categories
                    )TK ON TK.tk_id = T.tk_id
                    LEFT JOIN sun_it_tickets_detail TD ON TD.t_id = T.t_id
                    where TD.tech_viewed = 0
                    ORDER BY T.submit_time
    

    其他表也左键联接(忽略它)。

    这将只返回匹配的行,仅tech_viewsed=0,但我希望其他结果也“COUNT(TD.t_detail_id)作为‘User Comment’”,这样如果没有匹配项,将给出COUNT 0。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Gordon Linoff    8 年前

    您需要将条件移动到 on 条款

    select T.t_id as TicektID, TK.tk_category as Category,
           coalesce(T.contact_person, 'N/A') as Contact_Person,
           T.comment as Employee_Comment,
           COUNT(TD.t_detail_id) as num_comments, 
           T.t_status
    from sun_it_tickets T left join
         sun_it_ticket_categories tk
         on TK.tk_id = T.tk_id left join
         sun_it_tickets_detail TD 
         on TD.t_id = T.t_id and TD.tech_viewed = 0
    group by Category, Contact_Person, Employee_Comment, t_status
    order by max(T.submit_time);
    

    笔记:

    • 不要对列别名使用单引号。仅对字符串和日期常量使用单引号。
    • 所有非聚合列都应位于 group by .
    • 这个 order by 应该在
    • coalesce() 是ISO/ANSI标准函数,因此我更喜欢使用它,而不是数据库特定的替代方法。