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

时间:2013-06-20 16:40:44

标签: mysql sql select count

我在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 个答案:

答案 0 :(得分: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 Fiddle

答案 1 :(得分:0)

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

SELECT abbreviation, 
(SELECT COUNT(*) FROM courses C WHERE D.abbreviation = SUBSTRING(C.abbreviation, 0, 3)) AS c 
FROM departments D;

答案 2 :(得分: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;

答案 3 :(得分:0)

尝试一下

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