我有一个名为Category 和Posts 的表格。一个帖子可以属于多个类别。一个类别有很多帖子,它们之间的关系是多对多。我创建了一个新的弱实体 cat_post 表。在Category中,一条记录可以有很多child但不能是child的child。所以我想计算属于所有父记录的所有帖子。
分类表字段
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 的类别的每个父记录的所有帖子。
注意:如果类别记录有子记录,则该记录不会有帖子。
最佳答案
据我了解,这可以满足您的要求:
(在我的示例中,tender_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 对结果进行分组,并计算每个类别的每个帖子。
这是一个 example on sqlfiddle .
关于mysql - sql 计算所有记录属于具有多对多关系的父记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30230639/