简体   繁体   中英

MySQL UNION with COUNT aliasing

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?

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;
select sum(total) from 
(
SELECT COUNT(entryid) total FROM rh_entries
UNION
SELECT COUNT(pentryid) total FROM rh_playerentries WHERE playerid=79
) as t;

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM