开发者

mysql update groupwise max

I have the following table

 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;

For each channel_id I would like to find the row with the maximum acquire time and change value to NU开发者_运维问答LL, status to NULL and connected to 0. Is this possible? The manual says that you cannot update a table and select from the same table in a subquery...

Thank you for your time.


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


Try this.

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 
)

If that doesn't work, try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜