2012-06-22 138 views
1

我是PHP的新手,我對數據庫不太瞭解。我有如下一個用戶表:多個查詢與使用PDO的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中運行單個查詢和處理數據並獲取格式化數據或運行三個查詢並獲取格式化數據?

+0

思想:http://explainextended.com/2011/03/28/mysql-splitting-aggregate-queries/ – biziclop

回答

0

當您使用3個查詢時,您將向您的數據庫發送3個請求,這可能需要更長的時間才能處理1個請求。同樣,隨着桌子的尺寸增大,它甚至可能需要更長的時間。 使用PHP格式化數據將是更好的選擇,儘管它可能會使查詢變得複雜。

0

3合1的查詢:

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