tags:

views:

184

answers:

3

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.

+6  A: 

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
Eric
First option works great, seems my earlier (now deleted comment was due to caching), thanks for the solution.
Unkwntech
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 :)
Michael Buen
@Michael: Good catch! Thanks!
Eric
A: 

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;
LorenVS
You're limiting too early.
Eric
+2  A: 

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.

too much php