簡體   English   中英

SQL:從一個表獲取所有記錄和從第二個表中獲取記錄數?

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

假設有兩個表:

表A.

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

表B

commentID / messageID / Comment 
1         / 2         / This is a comment to the second message 
2         / 2         / This is another comment to the second message 
3         / 3         / This is a comment to the third message

表之間的關系是messageID字段。

我想要一個生成這樣的結果的查詢,其中我從表A中提取所有字段,以及表B中每條消息的注釋數計數,如下所示:

messageID  / Message                    / More...  / CommentCount
1          / This is the first message  / etc...   / 0
2          / This is the second message / etc...   / 2
3          / This is the third message  / etc...   / 1

我嘗試過這樣的事情:

SELECT tableA.*, count(commentID) as commentcount 
FROM tableA LEFT JOIN tableB ON tableA.messageID = tableB.messageID GROUP BY messageID

但它不起作用。 有任何想法嗎? 似乎應該可以在一個查詢中執行此操作。 我正在使用MSSQL。 謝謝你的幫助。

標量子查詢將起作用:

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

像往常一樣,通過不同的性能配置文件,可以通過很多方法來修飾這只貓。

使用GROUP BY ,輸出中的所有列都需要位於GROUP BY或聚合函數中 - 即使messageID中的其他列沒有變化,它們仍然需要位於GROUP BY

您可以使用CTE。

;WITH CTE_MessageCount (MessageId, Count)
AS
(
SELECT MessageId, Count(*) FROM TableB GROUP BY MessageId
) 

SELECT A.*, T.*
FROM tableA A JOIN CTE_MessageCount T ON A.messageID = T.MessageID

試試這個查詢:

SELECT a.*, b.msgCount
  FROM tableA a LEFT JOIN 
    ( SELECT messageID, COUNT(1) AS msgCount FROM tableB b GROUP BY messageID) b
        ON a.messageID =  b.messageID 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM