|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||||
|
|||||
|
how to count distinct elements, MySQL
Hi,
My problem has to do with counting records in a table. I would like to end up with an associative array $count, where each index in $count is the field value and each respective value in $count is the number of occurrences of that value in the table. To clarify, say I have a field "category", whose value must be one of several options (say "one", "two", or "three"). I do not know how many records there are in the table, there could be any number. Also, there could be any number of options for the "category" field, so a dynamic approach is necessary. This is what I have so far: php Code:
If anyone has any ideas about how to generate this information in an efficient manner please let me know. Thanks, Peter |
|
#2
|
|||
|
|||
|
RE: how to count distinct elements, MySQL
This query should work:
Code:
SELECT DISTINCT category,COUNT(category) AS cat_num FROM tablename GROUP BY category; |
|
#3
|
||||
|
||||
|
RE: how to count distinct elements, MySQL
brut's query should work, but there's more in there than you need (DISTINCT + GROUP BY is a little redundant). This is simplier:
Code:
SELECT category, COUNT(*) AS cat_num FROM tablename GROUP BY category |
|
#4
|
|||||
|
|||||
|
RE: how to count distinct elements, MySQL
Thanks a heap for the replies, much appreciated.
This is what I ended up with: php Code:
Code:
computersgeneral = 4 computershardware = 2 This works, but I think it looks horribly inefficient (two returned values in $result where only one is necessary) - do you know a better way to do it (e.g. a query that returns an associative array with [index == the column value] and [value == number of occurrences of column value])? Thank you very much, Peter |
|
#5
|
|||||
|
|||||
|
RE: how to count distinct elements, MySQL
$result is not an array, it's a mysql result identifier. You need to use mysql_fetch_array to get the next row of data from it.
php Code:
|
|
#6
|
|||||
|
|||||
|
RE: how to count distinct elements, MySQL
Ignore most what what I just posted. I must be drinking.
You need to repeatedly use mysql_fetch_array. The way you had it originally, you just got the first row returned. php Code:
|
![]() |
| Viewing: Codewalkers Forums > Other Technologies > Database Help > how to count distinct elements, MySQL |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|