[英]MySQL select Distinct records in 1 table and count each group based on values in another table
[英]Count records in a MySQL table based for each record of another table
我在 MySQL 数据库中有两个表 -
table_a
:
+----+---------+-------------+-----------------
| id | section | sub_section | ...other_fields
+----+---------+-------------+-----------------
| 1 | A | X |
| 2 | A | Y |
| 3 | A | Z |
| 4 | B | P |
| 5 | B | Q |
| 6 | C | L |
| 7 | C | M |
| 8 | C | N |
| 9 | C | O |
+----+---------+-------------+-----------------
table_b
:
+----+-------------+---------+-----------------
| id | sub_section | b_count | ...other_fields
+----+-------------+---------+-----------------
| 1 | X | 1 |
| 2 | Y | 1 |
| 3 | L | 0 |
| 4 | P | 1 |
| 5 | P | 1 |
| 6 | X | 0 |
| 7 | M | 1 |
| 8 | Y | 0 |
| 9 | Q | 1 |
+----+-------------+---------+-----------------
我想在 table_b 中找到b_count
的计数以及表 B 中sub_section
中每个不同section
的table_b
的table_a
-
预期结果:
+---------+--------------------+--------------+
| section | COUNT(sub_section) | SUM(b_count) |
+---------+--------------------+--------------+
| A | 4 | 2 |
| B | 3 | 3 |
| C | 2 | 1 |
+---------+--------------------+--------------+
一种方法是运行 Count(section) 查询次数,然后合并结果。
就像是:
SELECT 'A' AS section, COUNT(sub_section), SUM(b_count) FROM table_b WHERE sub_section IN (SELECT DISTINCT sub_section FROM table_a WHERE section='A')
UNION
SELECT 'B' AS section, COUNT(sub_section), SUM(b_count) FROM table_b WHERE sub_section IN (SELECT DISTINCT sub_section FROM table_a WHERE section='B')
UNION
SELECT 'C' AS section, COUNT(sub_section), SUM(b_count) FROM table_b WHERE sub_section IN (SELECT DISTINCT sub_section FROM table_a WHERE section='C');
有没有更好的方法在查询中执行此操作?
table_a
中的section
列表是动态的,可能会更改,我不想在每次值更改时更新我的查询。
SELECT t1.section, COUNT(DISTINCT t1.sub_section), SUM(t2.b_count)
FROM table_a t1
LEFT JOIN table_b t2 USING (sub_section)
GROUP BY t1.section;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.