sql - MySQL merge results into table from count of 2 other tables, matching ids -
i've got 3 tables: model, model_views, , model_views2. in effort have 1 column per row hold aggregated views, i've done migration make model this, new column views:
+---------------+---------------+------+-----+---------+----------------+ | field | type | null | key | default | | +---------------+---------------+------+-----+---------+----------------+ | id | int(11) | no | pri | null | auto_increment | | user_id | int(11) | no | | null | | | [...] | | | | | | | views | int(20) | yes | | 0 | | +---------------+---------------+------+-----+---------+----------------+
this columns model_views , model_views2 like:
+------------+------------------+------+-----+---------+----------------+ | field | type | null | key | default | | +------------+------------------+------+-----+---------+----------------+ | 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 gargantuan, both totalling in tens of millions of rows each. each row representative of 1 view, , terrible mess performance. far, i've got mysql command fetch count of rows representing single views in both of these tables, sorted model_id added up:
select model_id, sum(c) ( select model_views.model_id, count(*) c model_views group model_views.model_id union select model_views2.model_id, count(*) c model_views2 group model_views2.model_id) foo group model_id
so nice big table following:
+----------+--------+ | model_id | sum(c) | +----------+--------+ | 1 | 1451 | | [...] | | +----------+--------+
what safest route pulling off commands here on in merge values of sum(c) column model.views, matched model.id model_ids out of above sql query? want fill rows models still exist - there model_views referring rows in model table have been deleted.
you can use update
join
on subquery:
update model join ( select model_views.model_id, count(*) c model_views group model_views.model_id union select model_views2.model_id, count(*) c model_views2 group model_views2.model_id) toupdate on model.id = toupdate.model_id set model.views = toupdate.c
Comments
Post a Comment