Home > Database > Mysql Tutorial > Why Does MySQL Throw 'Invalid use of group function' and How to Fix It Using HAVING?

Why Does MySQL Throw 'Invalid use of group function' and How to Fix It Using HAVING?

Mary-Kate Olsen
Release: 2025-01-11 22:31:44
Original
829 people have browsed it

Why MySQL Throws "Invalid use of group function"

MySQL error: "Invalid use of group function" causes and solutions

In the given MySQL query, the "Invalid use of group function" error is due to the use of the COUNT function in the WHERE clause. WHERE clause filters rows before grouping, causing error.

Use the HAVING clause to solve the problem

To resolve this issue, replace the WHERE clause with a HAVING clause. The HAVING clause filters groups after grouping. In this example, the HAVING clause should check the count of supplier ID (sid) to make sure it is greater than or equal to 2.

The following is the corrected subquery:

<code class="language-sql">(
    SELECT c2.pid
    FROM Catalog AS c2
    WHERE c2.pid = c1.pid
    HAVING COUNT(c2.sid) >= 2
)</code>
Copy after login

Complete query with HAVING clause

Using the updated subquery, the complete query becomes:

<code class="language-sql">SELECT c1.pid                      -- 选择 pid
FROM Catalog AS c1                 -- 来自 Catalog 表
WHERE c1.pid IN (SELECT c2.pid   -- 其中 pid 在以下集合中:
    FROM Catalog AS c2             -- pids
    WHERE c2.pid = c1.pid
    HAVING COUNT(c2.sid) >= 2     -- 至少有两个对应的 sids
);</code>
Copy after login

This query will return the pids of parts supplied by at least two different suppliers.

The above is the detailed content of Why Does MySQL Throw 'Invalid use of group function' and How to Fix It Using HAVING?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template