Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql having and where clause on the same query

This is the code I have :

$sqlz = "SELECT t1.user_id, t2.status, t2.email 
         FROM coverages t1 
         LEFT JOIN users t2 ON t1.user_id = t2.user_id 
         GROUP BY t1.user_id  
         HAVING COUNT(t1.user_id) =".$value;

I would like to add this "WHERE users.email IS NOT NULL" When I do add it, it returns a white page / no results. which I know for a fact there are at least 200 results on the db that contain an email and and match that criteria.

this is an example of what I did that did not work:

 $sqlz =    "SELECT t1.user_id, t2.status, t2.email 
             FROM coverages t1 
             LEFT JOIN users t2 ON t1.user_id = t2.user_id
             WHERE users.email IS NOT NULL 
             GROUP BY t1.user_id  
             HAVING COUNT(t1.user_id) =".$value;
like image 587
cppit Avatar asked Jul 02 '12 00:07

cppit


People also ask

Can you use both HAVING and WHERE SQL?

Yes, an SQL query can contain a WHERE and HAVING clause. You will use these together when you want to extract (or filter) rows for a group of data using a WHERE clause and apply a condition on the aggregate using the HAVING clause.

Can you always move a condition from the WHERE clause to the HAVING clause?

Answer. Yes, you can absolutely apply a WHERE clause in a query that also utilizes a HAVING statement.

Can we use HAVING and GROUP BY together?

HAVING Clause always utilized in combination with GROUP BY Clause. HAVING Clause restricts the data on the group records rather than individual records.

Can we use GROUP BY and WHERE clause together in SQL?

Absolutely. It will result in filtering the records on your date range and then grouping it by each day where there is data.


1 Answers

I think you need to use t2 (alias) instead of users.

 $sqlz =    "SELECT t1.user_id, t2.status, t2.email 
             FROM coverages t1 
                     LEFT JOIN users t2 ON t1.user_id = t2.user_id
             WHERE t2.email IS NOT NULL 
             GROUP BY t1.user_id  
             HAVING COUNT(t1.user_id) = " .$value;
like image 98
John Woo Avatar answered Sep 28 '22 15:09

John Woo