简体   繁体   中英

MySQL throws error 1111 when I try to run my query, how do I fix my group by and having clauses?

I am running a query to find which service has been scheduled the least often and keep running into error 1111: invalid use of group function. I have tried reformatting my query a few times and cannot resolve the issue. Is there a different syntax I should use?

The service table contains service_id, service_description, and service_cost and the scheduled_service table contains scheduled_service_id, appointment_id, and service_id. I have tried rewording my query a few times and all give me the same error.

This is my most recent attempt.

SELECT s.service_id, COUNT(ss.scheduled_service_id) AS ' # Scheduled' 
FROM service s JOIN scheduled_service ss
ON s.service_id = ss.service_id
GROUP BY service_id
HAVING COUNT(ss.scheduled_service_id) =
(SELECT MIN(COUNT(scheduled_service_id)) FROM scheduled_service GROUP BY service_id);

I can get the count for all services performed using this query but trying to alter it to giving me just the minimum is what I cannot do.

SELECT service_id, COUNT(scheduled_service_id) AS '# Scheduled' 
FROM scheduled_service 
GROUP BY service_id ;

I am expecting to get the service that has been scheduled the least amount of times.

You can ORDER BY the count and then LIMIT the number of returned rows to 1.

SELECT s.service_id, COUNT(ss.scheduled_service_id) AS ' # Scheduled' 
FROM service s JOIN scheduled_service ss
ON s.service_id = ss.service_id
GROUP BY service_id
ORDER BY COUNT(ss.scheduled_service_id)
LIMIT 1

If you want the least often, you can use:

SELECT s.service_id, 
       COUNT(ss.scheduled_service_id) as num_scheduled
FROM service s JOIN
     scheduled_service ss
     ON s.service_id = ss.service_id
GROUP BY s.service_id
ORDER BY num_scheduled ASC
LIMIT 1;

This query doesn't actually require the JOIN , so you can do:

SELECT ss.service_id, 
       COUNT(ss.scheduled_service_id) as num_scheduled
FROM scheduled_service ss
GROUP BY ss.service_id
ORDER BY num_scheduled ASC
LIMIT 1;

Unless you want to count services that have been scheduled zero times. In that case, you want a LEFT JOIN :

If you want the least often, you can use:

SELECT s.service_id, 
       COUNT(ss.scheduled_service_id) as num_scheduled
FROM service s LEFT JOIN
     scheduled_service ss
     ON s.service_id = ss.service_id
GROUP BY s.service_id
ORDER BY num_scheduled ASC
LIMIT 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM