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.
The SQL WHERE ClauseThe WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.
The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With