Link to home
Start Free TrialLog in
Avatar of shwekhaw
shwekhaw

asked on

MySql Query question

First I am newbie to php and mysql. I am trying to do read some data from a table in most efficient way possible.
Here is a simple example of an table. Two columns are color and username
blue,user1
red,user2
yellow, user3
red,user4
blue,user5
red,user6

The array I want to get out of query is like this
red,3
blue,2
yellow,1

Normally, I would make
1. Select query for distinct color and get array fo colors and save in array A
2. Another query to get count for each color and save in array B
3. Then sort the array using array_multisort so that colors with the most username records is on the top (in above example order would be red,blue,yellow)

Can you get all three steps done in one query? If not, can you get step one and step two done in one query so array will be like (color,# of users) for all distinct colors.

ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shwekhaw
shwekhaw

ASKER

Nice it works. If I have another table that has two columns color,colorcode and I would like my results to be (colorcode,# of users) instead of (color,# of users) how do I modify your query to make it work?
I tried following and it is not working.
select colorcode, count(*) from colorcodetable,yourtable where colorcodetable.color=yourtable.color group by color order by count(*) desc
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It works when I change
group by color to
group by c.color

All good now. Thank you.