mysql 中不包含特定值的行数

count of rows that do not contain a particular value in mysql

我有一个 table 这样的 mysql。我需要获取不包含特定属性的不同 doc_id 的计数。比如属性是'product',结果应该是1,(即只有第4个doc_id不包含产品)

+--------+-----------+--------+
| 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  |

您可以在没有子查询的情况下使用 count(distinct):

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;