2015-07-06 27 views
0

我有一個像這樣的表是mysql。我需要獲得不包含特定屬性的獨特doc_id的計數。例如,如果屬性是「產品」,結果應該是1,在mysql中不包含特定值的行的數量

+--------+-----------+--------+ 
| doc_id | attribute | value | 
+--------+-----------+--------+ 
|  1 | product | mobile | 
|  1 | model  | lumia | 
|  1 | camera | 5mp | 
|  2 | product | mobile | 
|  2 | model  | lumia | 
|  2 | ram  | 1gb | 
|  3 | product | mobile | 
|  3 | year  | 2014 | 
|  3 | made-in | china | 
|  4 | brand  | apple | 
|  4 | model  | iphone | 
|  4 | camera | 5mp | 
|  5 | product | camera | 
|  5 | brand  | canon | 
|  5 | price  | 20000 | 
+0

如果是我,我會建立標準化僞物化視圖,然後查詢對抗。 – Strawberry

回答

2

你可以做到這一點,而無需使用count(distinct)子查詢(即,只有第4 DOC_ID不包含產品):

select count(distinct doc_id) - count(distinct case when attribute = 'product' then doc_id end) 
from table t; 

使用子查詢,你會通過doc_id第一聚集體,然後做計數:

select count(*) 
from (select doc_id, max(attribute = 'product') as has_product 
     from table t 
     group by doc_id 
    ) t 
where has_product = 0; 
相關問題