MySQL将结果从2个其他表的数量合并到表中,匹配id

时间:2013-07-21 20:36:03

标签: mysql sql

我有3个表:model,model_views和model_views2。为了使每行有一列来保存聚合视图,我已经完成了一次迁移,使模型看起来像这样,并为视图添加了一个新列:

+---------------+---------------+------+-----+---------+----------------+
| Field         | Type          | Null | Key | Default | Extra          |
+---------------+---------------+------+-----+---------+----------------+
| id            | int(11)       | NO   | PRI | NULL    | auto_increment |
| user_id       | int(11)       | NO   |     | NULL    |                |
|  [...]        |               |      |     |         |                |
| views         | int(20)       | YES  |     | 0       |                |
+---------------+---------------+------+-----+---------+----------------+

这就是model_views和model_views2的列:

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(11)          | NO   | PRI | NULL    | auto_increment |
| user_id    | smallint(5)      | NO   | MUL | NULL    |                |
| model_id   | smallint(5)      | NO   | MUL | NULL    |                |
| time       | int(10) unsigned | NO   |     | NULL    |                |
| ip_address | varchar(16)      | NO   | MUL | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

model_views和model_views2是庞大的,每个都有数千万行。每行代表一个视图,这对性能来说是一个糟糕的混乱。到目前为止,我已经有了这个MySQL命令来获取这两个表中单个视图的所有行的计数,按照model_id的加法排序:

SELECT model_id, SUM(c) FROM (
    SELECT model_views.model_id, COUNT(*) AS c FROM model_views
    GROUP BY model_views.model_id
    UNION ALL
    SELECT model_views2.model_id, COUNT(*) AS c FROM model_views2
    GROUP BY model_views2.model_id)
AS foo GROUP BY model_id

所以我得到了一个很好的大表,包含以下内容:

+----------+--------+
| model_id | SUM(c) |
+----------+--------+
| 1        | 1451   |
| [...]    |        |
+----------+--------+

从这里取出命令以将SUM(c)的值合并到列model.views中最安全的路由是什么,将model.id与我从上面的SQL查询中获得的model_ids匹配?我想只填充仍然存在的模型的行 - 可能有model_views引用模型表中已删除的行。

1 个答案:

答案 0 :(得分:1)

您可以在子查询中使用UPDATE JOIN

UPDATE model
   JOIN (
       SELECT model_views.model_id, COUNT(*) AS c 
       FROM model_views
       GROUP BY model_views.model_id
       UNION ALL
       SELECT model_views2.model_id, COUNT(*) AS c 
       FROM model_views2
       GROUP BY model_views2.model_id) toupdate ON model.id = toupdate.model_id
SET model.views = toupdate.c