Jump to content

Need help with mysql select statements


masteroleary

Recommended Posts

How do I add the mysql count function to a select statement that selects data from multiple tables.
In this example below I can select data from different columns and tables. I then have a select statement that counts the id in multiple tables. But when I put the two together I get the error shown in result 3.

Also, I use 'AS' to create an alias name for each piece of data. Although I do this for the 'COUNT' items in $querycount, results two give me 4 when there are only 2 rows, adding both count statements together. What is the correct way to retrieve the number of rows for each table individually without the COUNT statements adding together?

[code]$queryid = 'Select site.id AS siteid, shoot.id AS shootid From site, shoot';
$querycount = 'Select COUNT(site.id) AS sitecount, Count(shoot.id) AS shootcount From site, shoot';
$querymixed = 'Select COUNT(site.id) AS sitecount, Count(shoot.id) AS shootcount, site.id AS siteid, shoot.id AS shootid From site, shoot';
$resultid = mysql_query($queryid);
$resultcount = mysql_query($querycount);
$resultmixed = mysql_query($querymixed);

while($rowid = mysql_fetch_array($resultid, MYSQL_ASSOC)){
print_r($rowid);
}
echo '<br /><br />';
while($rowcount = mysql_fetch_array($resultcount, MYSQL_ASSOC)){
print_r($rowcount);
}
echo '<br /><br />';
while($rowmixed = mysql_fetch_array($resultmixed)){
print_r($rowmixed);
}[/code]

Result 1:
Array ( [siteid] => 1 [shootid] => 1 ) Array ( [siteid] => 2 [shootid] => 1 ) Array ( [siteid] => 1 [shootid] => 2 ) Array ( [siteid] => 2 [shootid] => 2 )

Result 2:
Array ( [sitecount] => 4 [shootcount] => 4 )

Result 3:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ...
Link to comment
https://forums.phpfreaks.com/topic/34601-need-help-with-mysql-select-statements/
Share on other sites

Dont ask me why this makes it work. I dont know sql yet and I really didnt understand the definitions for the keywords added (' GROUP BY ' & ' WITH ROLLUP' )

[code]$querymixed = 'Select COUNT(site.id) AS sitecount, Count(shoot.id) AS shootcount, site.id AS siteid, shoot.id AS shootid From site, shoot GROUP BY site.id, shoot.id WITH ROLLUP';[/code]

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.