12

My question is very similar to this one How to reference a custom field in SQL I have the following query:

SELECT * , (SELECT COUNT( id ) 
FROM cms_store_items
WHERE speaker = cms_store_items_speakers.id
) AS count
FROM cms_store_items_speakers
LIMIT 0 , 30

I need to add a WHERE clause that looks like WHERE count > 0 but when I do I get the error Unknown column 'count' in 'where clause' is there anyway for me to reference the custom field in my where clause without duplicating logic?

I could just place the logic for the where clause in my code but I don't want to send what may well be more then 1000 rows to the app if not needed, it just seems like a waste of resources.

3 Answers 3

24

Well, to do this strictly the way you're doing it:

select
*
from
(
    SELECT * , (SELECT COUNT( id ) 
    FROM cms_store_items
    WHERE speaker = cms_store_items_speakers.id
    ) AS count
    FROM cms_store_items_speakers
) a
where a.count > 0
LIMIT 0 , 30

It would probably be better to do the following, though. It makes good use of the having clause:

select
    s.id,
    s.col1,
    count(i.speaker) as count
from
    cms_store_items_speakers s
    left join cms_store_items i on
        s.id = i.speaker
group by
    s.id,
    s.col1
having
    count(i.speaker) > 0
limit 0, 30
Sign up to request clarification or add additional context in comments.

2 Comments

First option works great, seems my earlier (now deleted comment was due to caching), thanks for the solution.
change the count(*) to count(i.speaker), and the having count(*) to having count(i.speaker), just future-proof the code; if the need to count zero matches arises, then just change the inner join to left join, i'll upvote your answer :)
16

You can using HAVING clause instead:

...
) AS count
FROM cms_store_items_speakers
HAVING count > 0
LIMIT 0 , 30

HAVING is like WHERE but it is able to work on columns which are computed. Warning: HAVING works by pruning results after the rest of the query has been run - it is not a substitute for the WHERE clause.

Comments

0

I'm not 100% sure about mysql, but something like this should be very possible:

(SELECT 
     *
FROM
(
   SELECT cms_store_items_speakers.*,
          (SELECT COUNT(id) FROM cms_store_items
           WHERE speaker = cms_store_items_speakers.id) AS 'count'
   FROM cms_store_items_speakers)
   LIMIT 0, 30
)
WHERE count > 0;

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.