Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using having count() in exists clause

I am trying to make a SQL query where the subquery in an 'exists' clause has a 'having' clause. The strange thing is that. There is no error and the subquery works as a stand-alone query. However, the whole query gives exactly the same results with the 'having' clause as without.
This is kind of what my query looks like:

 SELECT X
   FROM A
  WHERE exists (
               SELECT X, count(distinct Y)
                 FROM B
             GROUP BY X
               HAVING count(distinct Y) > 2)  

So I'm trying to select the rows from A where X has more then two occurances of Y in B. However, the results also include records that do not exist in the subquery. What am I doing wrong here?

like image 913
Sander Avatar asked Dec 21 '22 21:12

Sander


1 Answers

You don't correlate the two queries:

SELECT  X
FROM    A
WHERE   (
        SELECT  COUNT(DISTINCT y)
        FROM    b
        WHERE   b.x = a.x
        ) > 2
like image 54
Quassnoi Avatar answered Jan 06 '23 08:01

Quassnoi