gpt4 book ai didi

mysql - 我如何将这个 MySQL 查询最小化为一个?

转载 作者:行者123 更新时间:2023-12-01 00:31:21 25 4
gpt4 key购买 nike

我有这三个查询,我想将其最小化为一个。我该怎么做?

    $query  = "SELECT COUNT(*) FROM states WHERE id = 1";
$query2 = "SELECT COUNT(*) FROM cities WHERE id = 5";
$query3 = "SELECT COUNT(*) FROM areas WHERE id = 3";

另外,如果有人指出一些可以帮助我练习和理解 MySQL 命令的很棒的网站或文章,我将不胜感激。非常感谢。

编辑:我希望脚本返回一个结果(变量)中合并的行数。

最佳答案

好吧,(我知道)在一个查询中执行此操作的唯一方法是:

SELECT 
(SELECT COUNT(*) FROM states WHERE id = 1) AS state_count,
(SELECT COUNT(*) FROM cities WHERE id = 5) AS city_count,
(SELECT COUNT(*) FROM areas WHERE id = 3) AS area_count

这几乎不能称为“优化”,因为还有 3 个表扫描,但无法避免这些扫描,因为您想在三个不同的表上进行 COUNT

编辑

如果您想要三个数字的总和,那么这就是答案:

SELECT 
(
(SELECT COUNT(*) FROM states WHERE id = 1)
+ (SELECT COUNT(*) FROM cities WHERE id = 5)
+ (SELECT COUNT(*) FROM areas WHERE id = 3)
) AS sum

关于mysql - 我如何将这个 MySQL 查询最小化为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5538684/

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