Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom field in WHERE clause of SQL query

Tags:

sql

mysql

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.

like image 980
UnkwnTech Avatar asked Aug 19 '09 01:08

UnkwnTech


People also ask

Can we use WHERE clause in SQL?

The SQL WHERE ClauseThe WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.

How do we use WHERE clause in SQL explain with an example?

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.


2 Answers

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.

like image 37
too much php Avatar answered Nov 09 '22 20:11

too much php


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
like image 151
Eric Avatar answered Nov 09 '22 18:11

Eric