MySQL:选择COUNT记录

时间:2011-06-30 12:42:12

标签: mysql

我正在尝试选择已准确订购1个订单的1000个客户。一切都在Orders表中。

  

Order中选择*计数(CustomerID)= 1限制1000

基本上所有记录在整个表中只有一个CustomerID出现。这将返回一个空结果集,表中有100,000个。

5 个答案:

答案 0 :(得分:4)

您需要GROUP才能(有意义地)使用HAVING子句。以下按预期工作:

SELECT
    *
FROM
    `Order`
GROUP BY
    CustomerID
HAVING
    COUNT(CustomerID) = 1
LIMIT 1000

<强>更新
添加WHERE(参见评论):

SELECT
    *
FROM
    `Order`
WHERE
    Language = 'EN'
GROUP BY
    CustomerID
HAVING
    COUNT(CustomerID) = 1
LIMIT 1000

答案 1 :(得分:1)

SELECT * FROM `Order`
GROUP BY CustomerID 
HAVING COUNT(CustomerID) = 1 
LIMIT 1000

答案 2 :(得分:0)

select count(CustomerID) as counter ,o.* from Order o
group by CustomerID having  counter  = 1  limit 1000

答案 3 :(得分:0)

添加group by以查询正确的输出,例如:

选择* 来自订单 按客户ID分组 有计数(CustomerID)= 1 限制1000

答案 4 :(得分:0)

SELECT CustomerID FROM Order GROUP BY CustomerID HAVING COUNT(*)= 1 LIMIT 1000