1

我是 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 中运行单个查询和处理数据并获取格式化数据或运行三个查询并获取格式化数据?

4

2 回答 2

0

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

于 2012-06-22T14:59:32.513 回答
0

三合一查询:

SELECT *

FROM
 (SELECT GENDER as gender,
   COUNT(GENDER) as gendercount 
  FROM userprofile 
  GROUP BY GENDER) AS by_gender

INNER JOIN 
 (SELECT AgeGroupId as agegroupid,
   COUNT(AgeGroupId) as agegroupcount 
  FROM userprofile 
  GROUP BY AgeGroupId) AS by_age

INNER JOIN 
 (SELECT Location as location,
   COUNT(Location) as locationcount 
  FROM userprofile 
  GROUP BY Location) AS by_loc
于 2012-06-22T15:15:09.437 回答