472,139 Members | 1,629 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,139 software developers and data experts.

Counting number of matches with one database query?

Hi,

I'm new to PHP and I have a question that I think has a simple answer
but I just can't figure it out so I'm really hoping that one of you
gurus can help me out.

I'm trying to return data from mysql database. I have over a thousand
records and each record has a "type" field with values ranging from 1
to 9.

I'm setting up an html table that has 9 cells and all I want to do is
count the total amount of types. For example, there are 140 records as
type 1, 300 records as type 2 etc.

Do I need to do 9 database querys or can this be done with one query?

Any and all help is appreciated!

Jul 17 '05 #1
2 1398
>I'm new to PHP and I have a question that I think has a simple answer
but I just can't figure it out so I'm really hoping that one of you
gurus can help me out.

I'm trying to return data from mysql database. I have over a thousand
records and each record has a "type" field with values ranging from 1
to 9.

I'm setting up an html table that has 9 cells and all I want to do is
count the total amount of types. For example, there are 140 records as
type 1, 300 records as type 2 etc.

Do I need to do 9 database querys or can this be done with one query?


select type, count(type) from mytable group by type order by type;

This has the advantage or disadvantage, depending on how you look at it,
of not returning a row for any type with NO records for it, and it also
returns rows for type 11 which is actually a mistype for type 1.

Another variant of this, good for "top 10" lists:

select type, count(type) as cnt from mytable group by type order
by cnt limit 10;

Gordon L. Burditt
Jul 17 '05 #2
Great help, thanks a lot!

Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Adam i Agnieszka Gasiorowski FNORD | last post: by
3 posts views Thread by Chris | last post: by
3 posts views Thread by Megan | last post: by
18 posts views Thread by ChadDiesel | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.