多个查询与使用PDO的php中的单个查询?

时间:2012-06-22 14:48:58

标签: php mysql pdo phpmyadmin

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

2 个答案:

答案 0 :(得分:0)

当您使用3个查询时,您将向您的数据库发送3个请求,这可能需要更长的时间来处理1个请求。此外,随着您的桌子大小的增加,甚至可能需要更长的时间。 使用PHP格式化数据将是一个更好的选择,尽管它可以使查询变得复杂。

答案 1 :(得分: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