How to count rows in one table based on another table in mysql

后端 未结 4 1204
慢半拍i
慢半拍i 2021-01-19 18:17

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

departments
    abbreviation | name
    -------------|-------------
             


        
相关标签:
4条回答
  • 2021-01-19 18:25

    Try this

    SELECT d.abbreviation, COUNT(*) num
    FROM departments d
    INNER JOIN courses c ON c.section LIKE CONCAT(d.abbreviation, "%")
    GROUP BY d.abbreviation
    
    0 讨论(0)
  • 2021-01-19 18:27
    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

    0 讨论(0)
  • 2021-01-19 18:40

    I quick solution, but not the best, could be:

    SELECT abbreviation, 
    (SELECT COUNT(*) FROM courses C WHERE D.abbreviation = SUBSTRING(C.abbreviation, 0, 3)) AS c 
    FROM departments D;
    
    0 讨论(0)
  • 2021-01-19 18:46

    Give this a shot:

    select
        d.abbreviation,
        count(d.abbreviation) count
    from
        departments d
    inner join
        courses c
    on (LOCATE(d.abbreviation,c.section) <> 0)
    group by d.abbreviation;
    
    0 讨论(0)
提交回复
热议问题