簡體   English   中英

具有COUNT別名的MySQL UNION

[英]MySQL UNION with COUNT aliasing

我試圖從兩個單獨的表中檢索兩個計數到一個SQL查詢以與PHP一起使用。 這是當前的SQl查詢:

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

這是我用來利用數據的PHP:$ result = mysql_query($ 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: 

顯然$ attendance ['attended']的設置不正確。 我是否對UNION或COUNT或AS的工作方式有所了解?

Union將兩個查詢的內容合並到一個表中。 您的查詢具有不同的列名,因此合並將無法正常進行。 您將需要類似:

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;

要擴展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
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM