【问题标题】:How to update values based on most common field?如何根据最常见的字段更新值?
【发布时间】:2013-07-22 09:24:00
【问题描述】:

我有一张桌子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

我想运行一个查询来自动更新 table2 Content,使用 table1 中最常见的 Content 为每个 ID。查询完成后,表 2 将是:

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

我尝试在ID 匹配时将table1 加入table2,但如果我将Content 设置为max(Content),它会显示无效。我该怎么办?

【问题讨论】:

  • 在问这类问题时,最好提供相关的 DDL 和/或 sqlfiddle
  • 嗯,什么是相关的DDL?

标签: mysql select join


【解决方案1】:

您可以使用相关子查询来做到这一点:

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;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多