mysql update groupwise max

时间:2011-04-19 01:57:15

标签: mysql groupwise-maximum

我有下表

 CREATE TABLE `data` (
`acquire_time` decimal(26,6) NOT NULL,
`sample_time` decimal(26,6) NOT NULL,
`channel_id` mediumint(8) unsigned NOT NULL,
`value` varchar(40) DEFAULT NULL,
`status` tinyint(3) unsigned DEFAULT NULL,
`connected` tinyint(1) unsigned NOT NULL,
PRIMARY KEY (`channel_id`,`acquire_time`),
UNIQUE KEY `index` (`channel_id`,`sample_time`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

对于每个channel_id,我想找到具有最大获取时间的行,并将值更改为NULL,将状态更改为NULL并连接到0.这可能吗?手册说您无法更新表并从子查询中的同一个表中进行选择...

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

试试这个。

update data data_1
set value = null, status = null
where not exists (
    select 1
    from data data_2
    where data_2.channel_id = data_1.channel_id
    and data_2.acquire_time > data_1.acquire_time 
)

如果这不起作用,请尝试:

update data as data_1
left join data as data_2
on data_2.channel_id = data_1.channel_id
and data_2.acquire_time > data_1.acquire_time
set data_1.value = null, data_1.status = null
where data_2.acquire_time is null

答案 1 :(得分:0)

update data join
(
    select channel_id, max(acquire_time) acquire_time
    from data
    group by channel_id
) x on x.channel_id = data.channel_id and x.acquire_time = data.acquire_time
set
    value = null,
    status = null,
    connected = 0