如何根据mysql中的另一个表计算一个表中的行数

How to count rows in one table based on another table in mysql(如何根据mysql中的另一个表计算一个表中的行数)
本文介绍了如何根据mysql中的另一个表计算一个表中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MySQL 数据库中有两个表.第一个是部门名称列表.

I have two tables in a MySQL database. The first one has a list of department names.

departments
    abbreviation | name
    -------------|-------------
    ACC          | accounting
    BUS          | business
    ...

第二个表列出了课程名称,其中包含系的缩写.

The second table has a list of courses with names that contain the department's abbreviation.

courses
    section      | name
    -------------|-------------
    ACC-101-01   | Intro to Accounting
    ACC-110-01   | More accounting
    BUS-200-02   | Business etc.
    ...

我想写一个查询,对于 departments 表中的每一行,给我一个 courses 表中的行数的计数我有的缩写.像这样的东西:

I'd like to write a query that will, for each row in the departments table, give me a count of how many rows in the courses table are like the abbreviation I have. Something such as this:

    abbreviation | num
    -------------|--------------
    ACC          | 2
    BUS          | 1
    ...

我可以通过查询为一个单独的部门执行此操作

I can do this for one individual department with the query

SELECT COUNT(*) FROM courses WHERE section LIKE '%ACC%'
    (gives me 2)

虽然我可以在 PHP 中循环并多次执行上述查询,但我更愿意在单个查询中执行.这是我想到的伪代码...

Although I could loop through in PHP and do the above query many times, I'd rather do it in a single query. This is the pseudocode I'm thinking of...

SELECT department.abbreviation, num FROM
    for each row in departments
        SELECT COUNT(*) AS num FROM classes WHERE section LIKE CONCAT('%',departments.abbreviation,'%)

有什么想法吗?

推荐答案

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

Sql Fiddle

这篇关于如何根据mysql中的另一个表计算一个表中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)