2012-02-09 116 views
1

我希望查找表中不同记录的总数。 我有一个表有以下的列用于查找不同行的Mysql查询显示不正确的结果

id, name, product, rating, manufacturer price 

这个拥有大约128行基于不同的列名有些重复。

我只需要选择不同的行:

select distinct name, product, rating, maufacturer, price from table 

这将返回47行

为了分页的目的,我需要找到不同的记录总数,所以我有另一个satatement:

select distinct count(name), product, rating, maufacturer, price from table 

但这返回128,而不是47

如何ç我得到不同行的总数?任何帮助都感激不尽。由于

回答

1

你有独特和计数逆转。

SELECT COUNT(DISTINCT column_name) FROM table_name 

另外,当计数时我会丢掉额外的字段,对于其他字段您的结果将是意想不到的。

+0

这样做的问题是,OP预期不同的所有名称,产品等栏目,而不仅仅是名称。这可能会减少47次重复。即使是1行,如果名称始终相同,其他值也会发生什么变化 – 2012-02-10 17:41:59

+1

没错,我总是对像这样的问题感到好奇,他们实际上试图做的是最终结果。 – jjs9534 2012-02-10 21:16:19

0

尝试增加GROUP BY name, product, rating, maufacturer, price条款

0

这将需要两倍运行实际查询......对于不同的INNER然后让这些作为单列的计数返回,然后加入该到原来选择不同...

select distinct 
     t1.product, 
     t1.rating, 
     t1.maufacturer, 
     t1.price, 
     JustTheCount.DistCnt 
    from 
     table t1, 
     (select count(*) as DistCnt 
      from (select distinct  
         t2.product, 
         t2.rating, 
         t2.maufacturer, 
         t2.price 
         from 
         table t2) 
    ) JustTheCount 
0

在下面的查询,你要使用不同的名称行自DISTINCT子句中的列name先:

SELECT DISTINCT name, product, rating, maufacturer, price FROM table 

然而,要获得同样的记录的计数,请使用以下格式:

SELECT COUNT(DISTINCT name) FROM table 

请注意,DISTINCT进入COUNT函数的内部,以便计算不同的名称。您可能不希望在计数查询中包含其他列,因为它们将是该组中的随机样本。当然,如果你想要一个随机样本,那么包含它们。

大多数应用程序将首先运行计数查询,然后查询返回结果。另请注意,COUNT(*)只是一个估算值,其值可能与实际返回的记录数不同。

SELECT DISTINCT COUNT(name), product FROM table甚至不是MySQL 4.x中的有效查询。您不能混合聚合和非聚合列。在5.x中,它将运行,但非聚合列的值将是该集合中的随机样本。

1

,如果你想获得计数的结果,或者如果你想运行一个不同的查询相同的查询它是不是很清楚。这里去两个解决方案。在结果作为新列:

select distinct name, product, rating, manufacturer, price, (
    select count(*) from (
     select distinct name, product, rating, manufacturer, price from table1 
    ) as resultCount) as resultCount 
from table1 

通知以前的解决方案将重复的每一行,这是不是很有效,甚至没有视觉吸引力的COUNT(*)。尝试运行两个查询一个获取的实际数据,而另一个得到的表中的记录相匹配的数据量:

select distinct name, product, rating, manufacturer, price from table1 

select count(*) from (
    select distinct name, product, rating, manufacturer, price from table1 
) as result 

希望这有助于