views:

18

answers:

2

If I have a query, such as:

select column1, (
    select count(*) from table2
) as some_count
from table1
where column1 = 'foo'

I can use column1 in the where clause, but if I try to add

and some_count > 0

then I get an error that some_count doesn't exist. How can I use that in a where clause?

+2  A: 

As is, the only way is to use a derived table:

SELECT x.*
  FROM (select column1, 
               (select count(*) from table2) as some_count
          from table1
         where column1 = 'foo') x
 WHERE x.some_count > 0

Do you realize that without correlation, some_count is going to return the same value for every row returned?

OMG Ponies
yes, this is just a quick example. But I never thought (or knew how) of using a derived table. I'll give it a try
Carson Myers
+4  A: 

Use HAVING

select column1, (
    select count(*) from table2
) as some_count
from table1
HAVING some_count > 0
zerkms
OMG Ponies
That's perfect, this is for a wordpress site so it's running MySQL, though I'm glad to see the pitfalls about oracle and sql server
Carson Myers