简体   繁体   English

如何在mysql 2中基于一个表对一个表中的行进行计数

[英]How to count rows in one table based on another table in mysql 2

I checked this answer but I have a problem. 我检查了这个答案,但是有问题。

SQL Fiddle (I changed INNER JOIN to LEFT JOIN ) SQL提琴 (我将INNER JOIN更改为LEFT JOIN

What if there is a row in my departments (DDD for example) and no association in the courses table . 如果我的departments有一行(例如DDD)并且courses表中没有关联怎么办?

As you can see in the fiddle the count for DDD department is 1 like the BUS department has even if there is no data for DDD department. 正如您在小提琴中看到的那样,即使没有DDD部门的数据,DDD部门的计数也像BUS部门一样为1。 I know that LEFT JOIN does this but how can I modify this ? 我知道LEFT JOIN ,但是我该如何修改呢?

How do I get count = 0 for the DDD department? 我如何获得DDD部门的count = 0?

Try COUNT(c.section) so when section results null for no association then in count it evaluates to zero 尝试使用COUNT(c.section)这样当section没有关联时结果为null时,计数为零

SELECT d.abbreviation
, COUNT(c.section) num
FROM departments d
LEFT JOIN courses c ON c.section LIKE CONCAT(d.abbreviation, "%")
GROUP BY d.abbreviation

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据mysql中的另一个表计算一个表中的行数 - How to count rows in one table based on another table in mysql MySQL根据另一个表中的日期对一个表中的行进行计数 - MySQL count rows in one table based on dates in another table MySQL对一个表中的选定行进行计数以更新另一表中的值 - MySQL count selected rows in one table to update value in another table 根据另一个表中的行数更新一个表中的MySQL列 - Update MySQL column in one table based on the number of rows in another table MySQL根据另一个表的行选择一个表中的不同行 - Mysql select distinct rows in one table based on rows of another 根据另一个表ID计算表行数 - count table rows based on another table id MySQL-如何根据另一个表中的条件对一个表中的条目进行计数(时间除外) - MySQL - How to count entries in one table based on criteria in another table (except when) MySql - 如何根据在另一个表中加入的多个值从一个表中 select 行 - MySql - how to select rows from one table based on multiple values joined in another table 如何使用联接基于另一个表中的行从一个表中获取mysql行? - How can I use joins to fetch mysql rows from one table based on rows that are found in another? 如何根据另外两个表的过滤器快速返回和计算一个表中的行数 - How to fast return and count rows from one table based on filter by two another tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM