一次查询中的多个计数

发布于 2024-12-17 03:09:16 字数 528 浏览 0 评论 0原文

这个查询不起作用。有人可以帮我吗?

$query = "SELECT 
    COUNT(WHERE Name='george') AS george_total,
    COUNT(WHERE Name='michael') AS michael_total,
    COUNT(WHERE Name='mike') AS mike_total 
FROM users WHERE Banned IS NOT '1' AND Active='yes' AND Logins>1 AND Registered_to_forum='1'";

$row=mysql_fetch_array($result);
echo "
    We found $row['george_total'] people with the name 'George' in our database,
    $row['michael_total'] with the name Michael
    and $row['mike_total'] with the name Mike.
";

This query doesn't work. Can someone help me please?

$query = "SELECT 
    COUNT(WHERE Name='george') AS george_total,
    COUNT(WHERE Name='michael') AS michael_total,
    COUNT(WHERE Name='mike') AS mike_total 
FROM users WHERE Banned IS NOT '1' AND Active='yes' AND Logins>1 AND Registered_to_forum='1'";

$row=mysql_fetch_array($result);
echo "
    We found $row['george_total'] people with the name 'George' in our database,
    $row['michael_total'] with the name Michael
    and $row['mike_total'] with the name Mike.
";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

几味少女 2024-12-24 03:09:16

您可以使用 CASE 语句以及 COUNTSUM

COUNT 版本如下。 COUNT 仅计算 NOT NULL 值,因此您可以使用任何非空列或常量而不是 1。

SELECT 
    COUNT(CASE WHEN Name='george' THEN 1 END) AS george_total,
    COUNT(CASE WHEN Name='michael' THEN 1 END) AS michael_total,
    COUNT(CASE WHEN Name='mike' THEN 1 END) AS mike_total /*.... rest of query*/

SUM 版本为

SELECT 
    SUM(CASE WHEN Name='george' THEN 1 ELSE 0 END) AS george_total,
    SUM(CASE WHEN Name='michael' THEN 1 ELSE 0 END) AS michael_total,
    SUM(CASE WHEN Name='mike' THEN 1 ELSE 0 END) AS mike_total /*.... rest 
                                                                   of query*/

You can use a CASE statement and either COUNT or SUM.

The COUNT version is below. COUNT only counts NOT NULL values so you can use any Non Null column or constant instead of 1.

SELECT 
    COUNT(CASE WHEN Name='george' THEN 1 END) AS george_total,
    COUNT(CASE WHEN Name='michael' THEN 1 END) AS michael_total,
    COUNT(CASE WHEN Name='mike' THEN 1 END) AS mike_total /*.... rest of query*/

The SUM version is

SELECT 
    SUM(CASE WHEN Name='george' THEN 1 ELSE 0 END) AS george_total,
    SUM(CASE WHEN Name='michael' THEN 1 ELSE 0 END) AS michael_total,
    SUM(CASE WHEN Name='mike' THEN 1 ELSE 0 END) AS mike_total /*.... rest 
                                                                   of query*/
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文