如果以下SELECT
返回0或没有行,我只想插入或更新一行。
SELECT (value = ? AND status = ? AND connected = ?)
FROM channels, data
WHERE data.channel_id = channels.channel_id AND channels.channel_name = ? AND sample_time < ?
ORDER BY sample_time DESC
LIMIT 1
基本上,它是一个只写更改的数据存档程序。也就是说,如果数据与前一个sample_time所写的数据不同,它只会为给定的sample_time写入数据。此SELECT
获取前一个sample_time的给定通道的数据,并将其与当前sample_time的数据进行比较。因此,如果返回0,即数据不同,则应该继续写入。如果还没有为此通道写入数据,那么它应该不返回任何行,并且应该写入新数据。以下是我编写数据的查询:
INSERT INTO data (acquire_time, sample_time, channel_id, value, status, connected)
SELECT ?, ?, channels.channel_id, ?, ?, ?
FROM channels
WHERE channel_name = ?
ON DUPLICATE KEY UPDATE acquire_time = ?, value = ?, status = ?, connected = ?
当前sample_time的新数据可能会使用ON DUPLICATE KEY UPDATE
覆盖当前sample_time的先前数据,而不是与前一个sample_time存储的数据相同。
重复键是channel_id和sample_time的组合。 channel_id和acquire_time上还有一个唯一索引。
感谢您的时间。
答案 0 :(得分:0)
在您做出以下澄清之后,我相信这会做您想做的事情:
INSERT INTO data (acquire_time, sample_time, channel_id, value, status, connected)
SELECT ?, ?, channels.channel_id, ?, ?, ?
FROM channels
WHERE channel_name = ?
AND NOT EXISTS (
SELECT 1
FROM (
SELECT value, status, connected
FROM channels, data
WHERE data.channel_id = channels.channel_id AND channels.channel_name = ?
AND sample_time < ?
ORDER BY sample_time DESC
LIMIT 1
) a
WHERE a.value = ? and a.status = ? and a.connected = ?
)
ON DUPLICATE KEY UPDATE acquire_time = ?, value = ?, status = ?, connected = ?;