Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all users where count() equals a specific value

Tags:

sql

php

mysql

   $sql = "SELECT * FROM cars WHERE COUNT(brand)='4'";
   $results = mysql_query($sql);
   $rows = mysql_fetch_array($results);
   print_r($rows);

the table cars has these columns:

id brand     price
0  bmw
1  corvette
2  mercedes
3  bmw
4  bmw
5  toyota
6  bmw
7  honda
8  lotus

this is what I am trying to do, return from the table 'cars' every brand that has 4 different cars. In this example bmw has 4 4 different cars is 4 different rows with the same brand name. so I am trying to echo the name of the brand where the total number of inventory is 4. I hope I made sense, any help would be appreciated.

EDIT: I tried SELECT * FROM cars LEFT JOIN users ON cars.user_id=users.user_id HAVING count(user_id) = 4 this is not working any ideas?

like image 585
cppit Avatar asked Jun 23 '12 04:06

cppit


1 Answers

SELECT brand FROM cars GROUP BY brand HAVING COUNT(brand) = 4

For you edit:

SELECT t1.brand, t2.email 
FROM cars t1  
LEFT JOIN users t2 ON t1.user_id = t2.user_id 
GROUP BY t1.brand HAVING COUNT(t1.brand) = 4
like image 80
xdazz Avatar answered Sep 19 '22 07:09

xdazz