[英]How to count rows in one table based on another table in mysql
I have two tables in a MySQL database. 我在MySQL数据库中有两个表。 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.
...
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. 我想编写一个查询,对于departments
表中的每一行,我会计算一下我在courses
表中有多少行的缩写。 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)
Although I could loop through in PHP and do the above query many times, I'd rather do it in a single query. 虽然我可以在PHP中循环并多次执行上述查询,但我宁愿在单个查询中执行此操作。 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,'%)
Any ideas? 有任何想法吗?
SELECT d.abbreviation, COUNT(*) num
FROM departments d
INNER JOIN courses c ON c.section LIKE CONCAT(d.abbreviation, "%")
GROUP BY d.abbreviation
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;
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;
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.