A quick article to remind me about this issue. Not sure whether it is specific to the Joomla Content Management System, but within the Joomla! CMS, an error 1054 comes up if you use the above statement.
Why?
The MySQL statement SELECT COUNT(DISTINCT name) FROM table is valid but I get what you mean and it's sometimes difficult to explain why you want to use it.
How?
Method #1: Add an alias to the field:
-- Note the alias for the table (select results) SELECT COUNT(t1.my_field) FROM (SELECT DISTINCT my_field FROM my_table) T1; -- Performance Improvement SELECT COUNT(1) FROM (SELECT DISTINCT my_field FROM my_table) T1;
- -- Note the alias for the table (select results)
- SELECT COUNT(t1.my_field) FROM (SELECT DISTINCT my_field FROM my_table) T1;
- -- Performance Improvement
- SELECT COUNT(1) FROM (SELECT DISTINCT my_field FROM my_table) T1;
Method #2: Count from results (my preference):
SELECT COUNT(my_field) FROM my_table GROUP BY my_field;
- SELECT COUNT(my_field) FROM my_table GROUP BY my_field;
Ones that didn't work for me:
Method #3: By grouping (NOT recommended for more complex queries):
SELECT COUNT(my_field) FROM my_table GROUP BY my_field;
Additional:
Not sure why method 3 is an accepted answer over the web because as soon as I put a WHERE clause in the statements and check the numbers, only method 1 and 2 return the correct number. I'm still unsure as to why WHERE...GROUP BY... doesn't return the same totals and will update this article when I figure it out.