2010-07-25 54 views
4

我想從兩個單獨的表中檢索兩個計數到一個SQL查詢使用PHP。這是當前的SQL查詢:MySQL聯盟與計數別名

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

這是我使用的利用數據的PHP: $結果= mysql_query($查詢);

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

我得到這樣的輸出:

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

顯然,$出勤[ '參加']沒有被正確設置。我在關於UNION,COUNT或AS如何工作方面缺少一些東西?

回答

3

聯合將兩個查詢的內容組合到一個表中。您的查詢具有不同的列名稱,因此合併將無法正常工作。你會想是這樣的:

SELECT 
    (SELECT COUNT(entryid) FROM rh_entries) as total, 
    (SELECT COUNT(pentryid) FROM rh_playerentries WHERE playerid=79) as attended; 
2

要擴大amccausl的提示,一旦你有一個表,你可以做的操作就可以了:

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

我嘗試了上面,它說: '每個派生表都必須有自己的別名 – Benny 2013-03-27 21:59:34

2
select sum(total) from 
(
SELECT COUNT(entryid) total FROM rh_entries 
UNION 
SELECT COUNT(pentryid) total FROM rh_playerentries WHERE playerid=79 
) as t;