MySQL希望从左表中获取所有结果,并仅使用条件过滤右表

时间:2018-08-13 17:09:50

标签: mysql sql

让我们假设我有票务表:

票务表:

t_id,发表评论

ticket_detail的表格: t_detail_id,t_id,注释,tech_viewed

我想这样做,

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

其他表也保持联接(忽略它)。

我想要什么?我想从'sun_it_tickets_detail'表中获取行数,其中tech_viewed =0。

这只会返回仅匹配tech_viewed = 0的行,但我希望其他结果也为“ COUNT(TD.t_detail_id)作为'User Comment',”如果没有匹配项,则此结果将为0。

1 个答案:

答案 0 :(得分:0)

您需要将条件移至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应该在group by列或聚合表达式上。
  • coalesce()是ISO / ANSI标准函数,因此我更喜欢将其用于特定于数据库的替代方案。