I have this queries that counts all rows taht match Site = $site:
$count= mysql_query("SELECT COUNT(DISTINCT `Site`) FROM `Ratings` WHERE `Site` = '$site'");
The query above gets the number of ratings for a $site. But I also need to know if the user already rated the site. I’m using use another COUNT for this:
SELECT COUNT(*) FROM `Ratings` WHERE `Site` = '$site' AND `UID` = '$uid'"
Is it possible to get the number of site matches and check if the user rated the site in one query? Thanks
Yes, it isn’t very straightforward but you can do this in one query. Try this:
This query will return you 1 row with 2 columns. The first column
num_ratingswill be the number of ratings for that particular site, and thealready_ratedwill tell you if that particular user has rated the site. (It will be either ‘YES’ or ‘NO’)The
ORDER BY already_rated DESCinsures that if the user has rated the site, it will return YES, because YES comes after NO in the alphabet. This is necessary because when you useCOUNT()the rows are being grouped together.EDIT: After further testing, the solution above WILL NOT WORK. Use this one instead.