让我们假设我有票务表:
票务表:
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。
答案 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标准函数,因此我更喜欢将其用于特定于数据库的替代方案。