如何根据 table2 中的某些特定列在 table1 中获取 COUNT
How can I get COUNT in table1 based on some specific columns in table2
我有以下 tables:
Post Table
+----+------------+--------------+
| id | is_deleted | is_published |
+----+------------+--------------+
| 1 | 0 | 1 |
| 2 | 0 | 1 |
| 3 | 0 | 1 |
| 4 | 0 | 0 |
| 5 | 1 | 1 |
+----+------------+--------------+l
标签Table
+----+---------+
| id | name |
+----+---------+
| 1 | Fashion |
| 2 | Tech |
+----+---------+
Post_Tag Table
+----+--------+---------+
| id | tag_id | post_id |
+----+--------+---------+
| 1 | 2 | 2 |
| 2 | 2 | 3 |
| 3 | 1 | 2 |
| 3 | 1 | 4 |
| 3 | 1 | 1 |
| 4 | 1 | 5 |
+----+--------+---------+
由上面的tables,tags和posts的关系存储在post_tagtable。
使用 post_tag table,我想计算有多少 post 绑定到 标签 .所以我写了这个查询来计算时尚标签的 posts:
SELECT COUNT(tp.id) as totalPost FROM `post_tags` tp WHERE tag_id = 1;
这导致这对时尚标签是正确的:
+-----------+
| totalPost |
+-----------+
| 4 |
+-----------+
现在,我的挑战是:
post 与 is_deleted 列 = true 不应计算在内。
post 与 is_published 列 = false 不应计算在内。
如果 post 同时具有 is_deleted 和 is_published列为true,不应计算在内。
因此,只有当 post is_published = true 和 is_deleted = false.
请问,我该如何实现这些?
您必须 JOIN
表并使用 WHERE
子句过滤掉行。
SELECT COUNT(tp.id) as totalPost
FROM post_tags tp
JOIN post p ON tp.post_id = p.id
WHERE tag_id = 1
AND p.is_deleted = 0
AND p.is_published = 1;
我有以下 tables:
Post Table
+----+------------+--------------+
| id | is_deleted | is_published |
+----+------------+--------------+
| 1 | 0 | 1 |
| 2 | 0 | 1 |
| 3 | 0 | 1 |
| 4 | 0 | 0 |
| 5 | 1 | 1 |
+----+------------+--------------+l
标签Table
+----+---------+
| id | name |
+----+---------+
| 1 | Fashion |
| 2 | Tech |
+----+---------+
Post_Tag Table
+----+--------+---------+
| id | tag_id | post_id |
+----+--------+---------+
| 1 | 2 | 2 |
| 2 | 2 | 3 |
| 3 | 1 | 2 |
| 3 | 1 | 4 |
| 3 | 1 | 1 |
| 4 | 1 | 5 |
+----+--------+---------+
由上面的tables,tags和posts的关系存储在post_tagtable。 使用 post_tag table,我想计算有多少 post 绑定到 标签 .所以我写了这个查询来计算时尚标签的 posts:
SELECT COUNT(tp.id) as totalPost FROM `post_tags` tp WHERE tag_id = 1;
这导致这对时尚标签是正确的:
+-----------+
| totalPost |
+-----------+
| 4 |
+-----------+
现在,我的挑战是:
post 与 is_deleted 列 = true 不应计算在内。
post 与 is_published 列 = false 不应计算在内。
如果 post 同时具有 is_deleted 和 is_published列为true,不应计算在内。
因此,只有当 post is_published = true 和 is_deleted = false.
请问,我该如何实现这些?
您必须 JOIN
表并使用 WHERE
子句过滤掉行。
SELECT COUNT(tp.id) as totalPost
FROM post_tags tp
JOIN post p ON tp.post_id = p.id
WHERE tag_id = 1
AND p.is_deleted = 0
AND p.is_published = 1;