## 我的数据

``````business_stats ( id SERIAL,
pk integer not null,
b_total integer,
PRIMARY KEY(pk)
);
``````

``````business_details (id SERIAL,
category CHARACTER VARYING,
feature_a CHARACTER VARYING,
feature_b CHARACTER VARYING,
feature_c CHARACTER VARYING
);
``````

``````datasets (id SERIAL,
pk integer not null,
category CHARACTER VARYING;
PRIMARY KEY(pk)
);
``````

## 我做了什么（错误）

``````UPDATE business_stats
SET b_total = agg.total
(  SELECT  d.pk, count(bd.id) total
INNER JOIN datasets AS d
ON bd.category = d.category
GROUP BY d.pk
) agg
WHERE b.pk = agg.pk;
``````

`````` | id | pk |  b_total  |
+----+----+-----------+
|  1 | 14 |  273611   |
|  2 | 15 |  273611   |
|  3 | 16 |  273611   |
|  4 | 17 |  273611   |
``````

`````` | pk |  agg.total  |
+----+-------------+
| 14 |    273611   |
| 15 |    407802   |
| 16 |    179996   |
| 17 |    815580   |
``````

## 问题

• 为什么会这样？
• 为什么WHERE子句不起作用？

#### 2 个答案:

``````UPDATE business_stats bs
SET b_total =
(  SELECT   count(c.id) total
INNER JOIN datasets AS d
ON bd.category = d.category
where d.pk=bs.pk
)
/*optional*/
where exists (SELECT  *
INNER JOIN datasets AS d
ON bd.category = d.category
where d.pk=bs.pk)
``````

``````UPDATE business_stats AS b
SET b_total = agg.total
FROM
(...) agg
WHERE b.pk = agg.pk;
``````