views:

115

answers:

2

I am trying to retrieve two counts from two separate tables into one SQL query to use with PHP. This is the current SQl query:

SELECT COUNT(entryid) AS total FROM rh_entries UNION SELECT COUNT(pentryid) AS attended FROM rh_playerentries WHERE playerid=79

This is the PHP I am using to utilize the data: $result = mysql_query($query);

$attendance = mysql_fetch_assoc($result);
echo "Total: " . $attendance['total'] 
 . " Attended: " . $attendance['attended'] 
 . " Percentage: " 
 . (int)$attendance['total'] / (int)$attendance['attended'] 
 . " <br />";

I am getting this output:

Warning: Division by zero in /home/content/g/V/i/gViscardi/html/guilds/sanctum/raidinfo/player.php on line 41
Total: 6 Attended: Percentage: 

Apparently the $attendance['attended'] is not being set properly. Am I missing something on how UNION or COUNT or AS works?

+1  A: 

Union combines the contents of two queries into a single table. Your queries have different column names, so the merge won't work properly. You'll want something like:

SELECT (SELECT COUNT(entryid) FROM rh_entries) as total, (SELECT COUNT(pentryid) FROM rh_playerentries WHERE playerid=79) as attended;
amccausl
+1  A: 

To expand on amccausl's tip, once you have that single table, you can do operations on it:

select sum(total) from 
(
SELECT COUNT(entryid) FROM rh_entries as total
UNION
SELECT COUNT(pentryid) as total FROM rh_playerentries WHERE playerid=79
)
Ben Guthrie