gpt4 book ai didi

php - 在 SQL 查询中使用声明的 "AS"变量

转载 作者:行者123 更新时间:2023-11-29 00:02:45 25 4
gpt4 key购买 nike

我有以下查询,但它不起作用:

$sql = "SELECT dma, COUNT(*) as dma_count, round(dma_count/32434 * 100) as dma_percent FROM {$table} where dma != '0' GROUP BY dma ORDER BY dma_count DESC;";

它不起作用的原因(我知道)是因为我在这部分 round(dma_count/32434 * 100) 中使用了 dma_count

正确的做法是什么?

编辑:

额外的挑战。我不想使用 32434,而是想使用一个变量。我得到这样的变量:

$get_total = "SELECT count(DISTINCT `exuid`) from {$table};";
$total = $dbh->query($get_total)->fetchAll(PDO::FETCH_ASSOC);

所以我的查询变成了(评论中推荐的修复)

$sql = "SELECT dma, COUNT(*) as dma_count, round(COUNT(*)/{$total} * 100) as dma_percent FROM {$table} where dma != '0' GROUP BY dma ORDER BY dma_count DESC;";

这不起作用,因为我认为 $total 的格式不对。我该如何解决这个问题?

再次编辑:

明白了! $total 只是我的行数,所以我用这个代替。

SELECT dma, COUNT(*) as dma_count, round(COUNT(*)/(SELECT COUNT(*) FROM {$table}) * 100,2) as dma_percent FROM {$table} where dma != '0' GROUP BY dma ORDER BY dma_count DESC;"

最佳答案

您可以在等式中使用 COUNT(*) 代替别名,或使用子查询的最终答案。如果可以使用连接,通常避免子查询。

关于php - 在 SQL 查询中使用声明的 "AS"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com