Counting number of joined rows in left join

后端 未结 3 2096
情歌与酒
情歌与酒 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:43

    How about something like this:

    SELECT m.MESSAGEID, sum((case when mp.messageid is not null then 1 else 0 end)) FROM MESSAGE m
    LEFT JOIN MESSAGEPART mp ON mp.MESSAGEID = m.MESSAGEID
    GROUP BY m.MESSAGEID;
    

    The COUNT() function will count every row, even if it has null. Using SUM() and CASE, you can count only non-null values.

    EDIT: A simpler version taken from the top comment:

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

    Hope that helps.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题