0

I have a table table1 like:

ID  | Content
-------------
1   | run2
2   | run3
3   | run1
2   | run2
2   | run2
2   | run1
2   | run2
2   | run1

And another table table2:

Content  | ID
----------------
runX     | 1
runX     | 2
runX     | 2
runX     | 3

I want to run a query to automatically update table2 Content using most common Content in table1 for each ID. That's it after the query, table 2 would be:

Content  | ID
----------------
run2     | 1
run2     | 2
run1     | 3

I tried joining table1 to table2 on ID match but if I set Content to max(Content) it says invalid. How can I go about this?

4

1 回答 1

0

您可以使用相关子查询执行此操作:

update table2
    set content = (select content
                   from table1 t1
                   where t1.id = table2.id
                   group by content
                   order by count(*) desc
                   limit 1
                  );

但是,这并不能消除table2. 您需要将此作为附加步骤。也许您会满足于返回结果的简单查询:

select id,
       (select content
        from table1 t1
        where t1.id = table2.id
        group by content
        order by count(*) desc
        limit 1
       ) as content
from table2;

您甚至可以将其直接保存到另一个表中。

编辑:

我很惊讶这些返回的结果不正确。这是在做正确的事吗?

select id,
       substring_index(group_concat(content order by cnt desc), ',', 1) as MostCommon
from (select id, content, count(*) as cnt desc
      from table1
      group by id
     ) t
group by id;

如果这不能产生您期望的值,那么我误解了这个问题。

于 2013-07-23T11:08:20.150 回答