我试图从两个单独的表中检索两个计数到一个 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 工作原理的信息?
最佳答案
联合将两个查询的内容合并到一个表中。您的查询具有不同的列名,因此合并将无法正常进行。你会想要这样的东西:
SELECT
(SELECT COUNT(entryid) FROM rh_entries) as total,
(SELECT COUNT(pentryid) FROM rh_playerentries WHERE playerid=79) as attended;
关于php - 带有 COUNT 别名的 MySQL UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3330376/