Counting number of joined rows in left join

后端 未结 3 2119
情歌与酒
情歌与酒 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 01:56

    Don't forget to use DISTINCT in case you will LEFT JOIN more than one table:

    SELECT m.MESSAGEID, COUNT(DISTINCT mp.MESSAGEID) FROM MESSAGE m
    LEFT JOIN MESSAGEPART mp ON mp.MESSAGEID = m.MESSAGEID
    GROUP BY m.MESSAGEID;
    

提交回复
热议问题