Counting number of joined rows in left join

后端 未结 3 2126
情歌与酒
情歌与酒 2020-12-29 01:21

I\'m trying to write an aggregate query in SQL which returns the count of all records joined to a given record in a table; If no records were joined to the given record, the

3条回答
  •  忘掉有多难
    2020-12-29 02:00

    You first want to count in your messaepart table before joining, i think. Try this:

       SELECT m.MessageId
            , COALESCE(c, 0) as myCount
         FROM MESSAGE m
    LEFT JOIN (SELECT MESSAGEID
                    , count(*) c 
                 FROM MESSAGEPART 
                GROUP BY MESSAGEID) mp
           ON mp.MESSAGEID = m.MESSAGEID
    

提交回复
热议问题