I’m newbie to PHP and I dont know much about database. I have one user table as below:
------------------------------------------------------------------------
userid|firstname|lastname|password|Emailaddress|gender|agegroup|location
------------------------------------------------------------------------
| | | | | | |
| | | | | | |
I want to get gender, agegroup and location count for particular column value. If I run single query then the data is not returning as per my need.
$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";
And if I run three different queries then I get somewhat I want.
$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";
So if I run three queries then I am getting formatted data that I want and if I run single query than i need to format that using PHP. So which one would be better? Running single query and process data in PHP and get formatted data or running three queries and get the formatted data?
When you would use 3 queries, you would be sending 3 requests to your DB which might take longer against just 1 request. Also as your table grows in size, it might even take longer.
Formatting data in PHP would be a better option, although it can make the query complicated to read.