在 MySQL 查询中一起使用 DISTINCT 和 COUNT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1002349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using DISTINCT and COUNT together in a MySQL Query
提问by Click Upvote
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
我想要的是获取与关键字关联的唯一产品 ID 的数量。同一个产品可能与一个关键字相关联两次或更多,但我希望每个产品 ID 只计算 1 次
回答by David
use
用
SELECT COUNT(DISTINCT productId) from table_name WHERE keyword='$keyword'
回答by Gratzy
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.
这允许您查看每个不同的 productid ID 有多少与关键字相关联。
回答by tekBlues
You were close :-)
你很接近:-)
select count(distinct productId) from table_name where keyword='$keyword'
回答by Alistair Hart
FYI, this is probably faster,
仅供参考,这可能更快,
SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp
than this,
比这个,
SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'
回答by George SEDRA
What the hell of all this work anthers
所有这些工作到底是什么花药
it's too simple
这太简单了
if you want a list of how much productId in each keyword here it's the code
如果您想要每个关键字中有多少 productId 的列表,这里是代码
SELECT count(productId), keyword FROM `Table_name` GROUP BY keyword;
回答by Rhalp Darren Cabrera
SELECTING DISTINCT PRODUCT AND DISPLAY COUNT PER PRODUCT
选择不同的产品并展示每个产品的数量
for another answer about this type of question this is my another answer for getting count of product base on product name distinct like this sample below:
对于关于此类问题的另一个答案,这是我根据不同的产品名称获取产品数量的另一个答案,如下面的示例:
select * FROM Product
SELECT DISTINCT(Product_Name),
(SELECT COUNT(Product_Name)
from Product WHERE Product_Name = Prod.Product_Name)
as `Product_Count`
from Product as Prod
Record Count: 4; Execution Time: 2ms
记录数:4;执行时间:2ms
回答by Macarse
Isn't it better with a group by? Something like:
跟团不是更好吗?就像是:
SELECT COUNT(*) FROM t1 GROUP BY keywork;