简体   繁体   中英

How do I use a field that is a result of a subquery within a condition?

Here is the query I'm trying to execute, and it's supposed to return a table containing data for the pools that are not full (members_nr < members_max).

SELECT id, name,
(
    SELECT COUNT(*) FROM pools_entries WHERE pool_id=p.id AND pending=0
) AS members_nr,
members_max, open
FROM pools p
WHERE id IN(1,2,3,4) AND members_nr < members_max;

The problem is MySQL won't recognize members_nr as a field since it's a result from a subquery. Is there a logic solution to this little issue?

Any help will be much appreciated :)

NB is correct, you need the having clause. But for the sake of the googler's i'll share a little knowledge.

The WHERE clause is used for restricting the resultset to specific records, it is also used for optimisation. Mysql uses the WHERE clause to identify which index's it can use to speed up the query.

The HAVING clause is executed right at the end of the query. It is used for filtering the recordset. So imagine you have a list of stuff from the database that matches your WHERE clause. You can then use HAVING to filter that list down further on some set conditions.

My basic rule of thumb is: if you need to select based on a column's value, use WHERE, if you need to select based on the value of something which is not a column in the table, use HAVING.

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