我有一張record桌子和它的comment桌子,比如:
| commentId | relatedRecordId | isRead |
|----------- ----------------- --------|
| 1 | 1 | TRUE |
| 2 | 1 | FALSE |
| 3 | 1 | FALSE |
現在我想選擇newCommentCount和allCommentCount作為服務器對瀏覽器的回應。有沒有辦法在一個 SQL 中選擇這兩個欄位?
我試過這個:
SELECT `isRead`, count(*) AS cnt FROM comment WHERE relatedRecordId=1 GROUP BY `isRead`
| isRead | cnt |
| FALSE | 2 |
| TRUE | 1 |
但是,我必須使用特殊的資料結構對其進行映射并將cnt兩行中的欄位相加,才能allCommentCount使用上層編程語言得到。我想知道我是否可以僅通過 SQL 一步獲得以下格式的資料:
| newCommentCount | allCommentCount |
|----------------- -----------------|
| 2 | 3 |
我什至不知道如何描述這個問題。所以我在 Google 和 Stackoverflow 中沒有任何搜索結果。(可能是因為我的英語不好)
uj5u.com熱心網友回復:
使用條件聚合:
SELECT SUM(NOT isRead) AS newCommentCount, COUNT(*) AS allCommentCount
FROM comment
WHERE relatedRecordId = 1;
uj5u.com熱心網友回復:
如果我理解你想要顯示 newComments Count 和所有評論的總和,那么你可以這樣做
SELECT SUM ( CASE WHEN isRead=false THEN 1 ELSE 0 END ) AS newComment,
Count(*) AS AllComments From comments where relatedRecord=1
你也可以為它制作存盤程序。
uj5u.com熱心網友回復:
要水平放置兩個結果集,只要結果集中的行數匹配,您就可以像在 SELECT CLAUSE 中對運算式使用子查詢一樣簡單:
select (select count(*) from c_table where isread=false and relatedRecordId=1 ) as newCommentCount,
count(*) as allCommentCount
from c_table where relatedRecordId=1;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454343.html
上一篇:如果它們匹配,則連接行值?
