SQL: Get all records from one table AND a count of records from a second table?

前端 未结 3 1785
我寻月下人不归
我寻月下人不归 2021-01-12 13:15

Say there are two tables:

TABLE A

messageID / Message                     / More..
1         / This is the first message   / Etc..
2         


        
3条回答
  •  悲哀的现实
    2021-01-12 14:02

    Scalar subquery will work:

    SELECT tableA.*
        ,(SELECT count(commentID) FROM tableB WHERE tableA.messageID = tableB.messageID) as commentcount 
    FROM tableA
    

    As usual, there are a lot of ways to skin this cat, with varying performance profiles.

    When using a GROUP BY, all columns in the output either need to be in the GROUP BY or in aggregate functions - even though there is no variation in the other columns within a messageID, they still would need to be in the GROUP BY.

提交回复
热议问题