Jump to content

Help with Counting a Query


limitphp

Recommended Posts

I have a query that I use only to count the rows:

<?php
$sqlRowCount = "SELECT COUNT(*) FROM vote, artist, songs WHERE vote.artistID=artist.artistID AND vote.songID=songs.songID AND songs.genre IN ($genres) AND vote.Date > NOW()-INTERVAL $time DAY GROUP BY vote.songID ORDER BY COUNT(vote.songID) DESC";  
$resultRowCount = mysql_query($sqlRowCount) or die (mysql_error()); 
$fetchRowCount = mysql_fetch_row($resultRowCount);  
$numrows = $fetchRowCount[0]; 

 

then I use the same query (which I will eventually put limits on)

<?php
$queryVote = "SELECT vote.artistID, vote.songID, vote.Date, artist.artistName, artist.artistNameHash, songs.songName, songs.genre, COUNT(vote.songID) FROM vote, artist, songs WHERE vote.artistID=artist.artistID AND vote.songID=songs.songID AND songs.genre IN ($genres) AND vote.Date > NOW()-INTERVAL $time DAY GROUP BY vote.songID ORDER BY COUNT(vote.songID) DESC";
$resultVote = mysql_query($queryVote) or die (mysql_error());

 

Only the first query returns a lower number than the second query.

The first one is returning 4 and the second query returns 7 results.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/139891-help-with-counting-a-query/
Share on other sites

Those results make sense. With a group by, you get a count for each group. So the first query (with the group by) was returning multiple records. When the group by was removed you were returning one record of the total count.

 

Example Data

id | name
a  | Bob
b  | Jim
a  | Dave
c  | Mary
a  | Alice
c  | Rob
d  | Mike

 

This query

SELECT COUNT(*) FROM table GROUP BY id

Would return:

3 (for the a records)

1 (for the b records)

2 (for the c records)

1 (for the d records)

 

This query

SELECT COUNT(*) FROM table

Would return:

7

 

Those results make sense. With a group by, you get a count for each group. So the first query (with the group by) was returning multiple records. When the group by was removed you were returning one record of the total count.

 

Example Data

id | name
a  | Bob
b  | Jim
a  | Dave
c  | Mary
a  | Alice
c  | Rob
d  | Mike

 

This query

SELECT COUNT(*) FROM table GROUP BY id

Would return:

3 (for the a records)

1 (for the b records)

2 (for the c records)

1 (for the d records)

 

This query

SELECT COUNT(*) FROM table

Would return:

7

 

 

but now when I removed the group by...the results are higher than the second query....

how can I make it be the same?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.