0

I have a query problem with count. I want to have a column with the number of persons registered to the course.

So far, this is my query:

select
  courses.id, 
  name, 
  location, 
  capacity, 
  (
    SELECT count(courses_requests.IDcourse) 
    FROM courses_requests, courses
    WHERE courses_requests.IDcourse = courses.id AND status != "rejected"
  ) as Registered, 
  begin_date, 
  end_date,  
  price, 
  active
from courses

But this is giving me problems, it displays the same value for all rows, even if the course doesn't have persons registered in the course

E.G

Capacity Registered
2        1
30       1

3 Answers 3

1

It may be simplier to aggregate the outer select, to eliminate the subquery, so something like:

SELECT      c.id, 
            c.name, 
            c.location, 
            c.capacity, 
            COUNT(cr.IDcourse) AS RequestCount 
            c.begin_date, 
            c.end_date,  
            c.price, 
            c.active

FROM        courses c

INNER JOIN  courses_requests cr
    ON      cr.IDcourse = c.id 
    AND     status != "rejected"

GROUP BY    c.id, 
            c.name, 
            c.location, 
            c.capacity, 
            c.begin_date, 
            c.end_date,  
            c.price, 
            c.active
Sign up to request clarification or add additional context in comments.

1 Comment

Thank, this works!. Although I had to edit it a little bit. I changed the inner join to left join and an ifnull function in the count to return 0
0

You should connect your subquery to main query:

select courses.id, 
    courses.name, 
    courses.location, 
    courses.capacity, 
    (SELECT count(courses_requests.IDcourse) 
          FROM    courses_requests, 
           WHERE courses_requests.ID = courses.id 
            and status != "rejected" ) as Registered, 
    begin_date, 
    end_date,  
    price, 
    active
    from courses

Comments

0

You can use join to simplify your query ans using SUM() with a condition will give you the count

select
  c.id, 
  c.name, 
  c.location, 
  c.capacity, 
  SUM(cr.status != "rejected") as Registered, 
  c.begin_date, 
  c.end_date,  
  c.price, 
  c.active
from courses c
JOIN courses_requests cr ON (cr.IDcourse = c.id)
GROUP BY c.id

Comments

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.