![](/img/trans.png)
[英]Getting all records in many-to-many relationship even if the relationship is missing
[英]sql counting all records belong to parent record with many to may relationship
我有一個名為Category和Posts的表。 一個帖子可以屬於多個類別。 一個類別有很多職位,它們之間的關系是多對多的 。 我創建了一個新的弱實體cat_post表。 在類別中 ,記錄可以有多個孩子,但不能有一個孩子。 所以我想計算所有帖子屬於所有父記錄。
類別表字段
id category_id
1
2
3
4 1
5 1
6 2
7 2
帖子表
id
1
2
3
cat_post表字段
tender_id category_id
1 4
2 5
3 3
3 5
4 6
4 4
類別:
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
+-----------------+--------------+------+-----+---------+----------------+
| category_id | int(11) | NO | NULL | NULL | NULL |
+-----------------+--------------+------+-----+---------+----------------+
帖子:
+-------------------+--------------+------+-----+---------+-----------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-----------+
| id | int(11) | NO | PRI | NULL | |
+-------------------+--------------+------+-----+---------+-----------+
cat_post:
+---------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------+------+-----+---------+-------+
| category_id | int(11) | NO | PRI | NULL | |
| post_id | int(11) | NO | PRI | NULL | |
+---------------+---------+------+-----+---------+-------+
我想計算屬於父記錄的所有帖子。 換句話說,計算類別的每個父記錄的所有帖子,其中category.category_id僅為null。
注意 :如果類別記錄中有一個孩子,那么該記錄將沒有帖子。
據我了解,這將滿足您的要求:
(在我的示例中bid_id名為post_id )
SELECT c.id, count(p.id) as postcount
FROM Category AS c
INNER JOIN cat_post AS cp ON c.id = cp.category_id
INNER JOIN Posts AS p ON p.id = cp.post_id
WHERE c.category_id is null
GROUP BY c.id
這將聯接所有表,並且僅選擇那些父級的記錄(類別中沒有category_id)。 然后將結果按category.id分組,並對每個類別的每個帖子計數。
這是sqlfiddle上的示例 。
您應該將CATEGORY表與其自身連接起來,即使有0個孩子,也要計算Categories
。 然后在我使用OR
的Join中連接cat_post
表,以處理主類別沒有子類別的情況。 另外,如果您只想對每個類別的DISTINCT帖子進行計數,請使用COUNT(DISTINCT)(例如,如果一個帖子屬於一個父類別的兩個不同的孩子,那么您應該將其視為一兩個嗎?)
SELECT A.Id, COUNT(DISTINCT cat_post.Post_Id) FROM Category A
LEFT JOIN Category B on A.Id=B.Category_id
LEFT JOIN cat_post ON (cat_post.category_id = B.Id)
or
(cat_post.category_id = A.Id)
WHERE A.Category_Id is NULL
GROUP BY A.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.