gpt4 book ai didi

php - 使用 PDO 在 PHP 中进行多个查询与单个查询?

转载 作者:行者123 更新时间:2023-11-30 23:30:05 25 4
gpt4 key购买 nike

我是 PHP 新手,对数据库了解不多。我有一个用户表如下:

------------------------------------------------------------------------
userid|firstname|lastname|password|Emailaddress|gender|agegroup|location
------------------------------------------------------------------------
| | | | | | |
| | | | | | |

我想获取特定列值的 genderagegrouplocation 计数。如果我运行单个查询,则数据不会根据我的需要返回。

$query="SELECT AgeGroupId as agegroupid,
count(AgeGroupId) as agegroupcount,
GENDER as gender,
count(GENDER) as gendercount,
Location as location,
count(Location) as locationcount
FROM userprofile
GROUP BY AgeGroupId, GENDER, Location";

如果我运行三个不同的查询,那么我会得到一些我想要的。

$query1="SELECT GENDER as gender,
count(GENDER) as gendercount
FROM userprofile
GROUP BY GENDER";
$query2="SELECT AgeGroupId as agegroupid,
count(AgeGroupId) as agegroupcount
FROM userprofile
GROUP BY AgeGroupId";
$query3="SELECT Location as location,
count(Location) as locationcount
FROM userprofile
GROUP BY Location";

因此,如果我运行三个查询,那么我将获得我想要的格式化数据,如果我运行单个查询,则我需要使用 PHP 对其进行格式化。那么哪一个会更好呢?在 PHP 中运行单个查询并处理数据并获取格式化数据,还是运行三个查询并获取格式化数据?

最佳答案

当您使用 3 个查询时,您将向您的数据库发送 3 个请求,而仅发送 1 个请求可能需要更长的时间。此外,随着您的 table 越来越大,它甚至可能需要更长的时间。在 PHP 中格式化数据将是一个更好的选择,尽管它会使查询变得难以阅读。

关于php - 使用 PDO 在 PHP 中进行多个查询与单个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11158596/

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