4

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

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

第二个表有一个课程列表,其名称包含部门的缩写。

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

我想编写一个查询,对于departments表中的每一行,我都会计算表中有多少行courses就像我拥有的​​缩写一样。像这样的东西:

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

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

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

尽管我可以在 PHP 中循环并多次执行上述查询,但我宁愿在单个查询中执行此操作。这是我正在考虑的伪代码...

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

有任何想法吗?

4

4 回答 4

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

Sql 小提琴

于 2013-06-20T16:50:38.703 回答
0

我快速的解决方案,但不是最好的,可能是:

SELECT abbreviation, 
(SELECT COUNT(*) FROM courses C WHERE D.abbreviation = SUBSTRING(C.abbreviation, 0, 3)) AS c 
FROM departments D;
于 2013-06-20T16:54:12.243 回答
0

试一试:

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;
于 2013-06-20T17:17:19.077 回答
0

尝试这个

SELECT d.abbreviation, COUNT(*) num
FROM departments d
INNER JOIN courses c ON c.section LIKE CONCAT(d.abbreviation, "%")
GROUP BY d.abbreviation
于 2018-09-06T07:16:23.567 回答