2013-07-23 36 views
0

我有一個表像table1如何根據最常見的字段更新值?

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

而另一臺table2

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

我想運行一個查詢,以表1中使用最普遍的Content每個ID自動更新表2 Content。查詢後就是這樣,表2是:

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

我試着加入表1參見表2上ID的比賽,但如果我設置Contentmax(Content)它說無效。我怎麼去解決這個問題?

+1

當提出這些問題時,總是很好地提供相關的DDL和/或sqlfiddle – Strawberry

+0

嗯,相關的DDL是什麼? – rtuner

回答

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; 

如果這不會產生您期望的值,那麼我誤解了這個問題。

+0

浪費了很多時間,但產生了錯誤的結果。 – rtuner