Using DISTINCT and COUNT together in a MySQL Query

Viewed 222402

Is something like this possible:

SELECT DISTINCT COUNT(productId) WHERE keyword='$keyword'

What I want is to get the number of unique product Ids which are associated with a keyword. The same product may be associated twice with a keyword, or more, but i would like only 1 time to be counted per product ID

7 Answers

use

SELECT COUNT(DISTINCT productId) from  table_name WHERE keyword='$keyword'

I would do something like this:

Select count(*), productid
from products
where keyword = '$keyword'
group by productid

that will give you a list like

count(*)    productid  
----------------------
 5           12345   
 3           93884   
 9           93493    

This allows you to see how many of each distinct productid ID is associated with the keyword.

You were close :-)

select count(distinct productId) from table_name where keyword='$keyword'

Isn't it better with a group by? Something like:

SELECT COUNT(*) FROM t1 GROUP BY keywork;
Related