4

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.
    ...

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)

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,'%)

Any ideas?

4 Answers 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 Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

It works! And in a lot less code than I was expecting. And in a lot less time than I expected too. Thanks!!
0

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;

1 Comment

Actually I prefer Steve's answer
0

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;

Comments

0

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

1 Comment

Welcome to StackOverflow! It seems like you're asking a follow-up question here, rather than giving a new answer. If that's the case, you should ask a whole new question, not post it as an answer here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.