MySQL-更新所有记录以匹配组中的最大值 [英] MySQL - updating all records to match max value in group

查看:184
本文介绍了MySQL-更新所有记录以匹配组中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的交易表

id , name , code  ,  flag 
1 ,  john , 1234-3,   2
2 ,  joe  , 1111-2,   1
3 ,  paul , 1234-3,   3
4 ,  asdf , 1234-3,   3
5 ,  asdf , 1111-2,   5
6 ,  asdf , 1234-3,   8
7,   asdf , 1234-3,   0

基本上,我要做的是将标志"字段中的所有数字设置为与特定代码相关的最大值.

Basically, what I want to do is set all numbers in the 'flag' feild to the max value related to a specific code.

因此,在代码1234-3的情况下,应使用标记为num 8的该代码更新所有标记 在1111-2的情况下,它需要使用5将该代码更新所有标志.

So in in the case of code 1234-3 it should update all flags with that code with flag num 8 in the case of 1111-2, it needs to update all flags with that code with 5.

我想将其转换为该表

id , name , code  ,  flag 
1 ,  john , 1234-3,   8
2 ,  joe  , 1111-2,   5
3 ,  paul , 1234-3,   8
4 ,  asdf , 1234-3,   8
5 ,  asdf , 1111-2,   5
6 ,  asdf , 1234-3,   8
7 ,  asdf , 1234-3,   8

如果可能的话,我只想在MySQL中做到这一点.有大量的数据.

I'd like to do this in MySQL purely if possible. There is a very large set of data.

推荐答案

UPDATE  t_transaction tu
JOIN    (
        SELECT  code, MAX(flag) AS flag
        FROM    t_transaction
        GROUP BY
                code
        ) t
ON      tu.code = t.code
SET     tu.flag = t.flag

这篇关于MySQL-更新所有记录以匹配组中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆