【问题标题】:Conditional Select and Update rows with previous/next rows条件选择和更新行与前/后行
【发布时间】:2020-11-04 08:00:48
【问题描述】:

我有一个表,其列“id”在 SQLite 中是自动递增的。在某些记录中,我的值为零。我想 1. 选择并 2. 更新它们。
条件如下:如果col1(=下例中的t)值等于下一行,则逐行更新,否则使用上一行进行更新。这里 next 表示 id + 1,previous 表示 id - 1。
我怎样才能做到这一点? (我需要 2 个查询:一个用于根据上述条件进行选择,另一个用于更新)

这个查询返回那些值为零的记录:

SELECT * FROM myTable
WHERE col2 = 0 

返回:

id    t     col2  col3 .....  coln
15  19:48     0     0  .....    0
23  20:53     0     0  .....    0

样本数据:

id    t     col2  col3 .....  coln
14  19:47     5    6   .....    7
15  19:48     0    0   .....    0
16  19:49     10   11  .....    12
...
22  20:52     15   16  .....    17
23  20:53     0     0  .....    0
24  20:53     20   21  .....    22

预期结果:

id    t     col2  col3 .....  coln
15  19:48     5    6   .....    7
23  20:53     20   21  .....    22

【问题讨论】:

  • 发布样本数据和该样本数据的预期结果以澄清,最好在小提琴中:dbfiddle.uk/?rdbms=sqlite_3.27
  • 为什么更新了 id=15 的行? id=14 或 id=16 的行中的 t 不等于该行的 t。
  • id=15 的行已更新,因为它的 col2,col3,... 的值为零。row=15 中的时间(t 字段)不等于 row=16 中的时间,所以行=14 用于填充这些零值。在 row=23 中,时间等于 row=24,所以第 24 行用于填充 row=23 中的零

标签: sql sqlite


【解决方案1】:

如果包含t 的相同值,则使用返回下一行或上一行的子查询:

update tablename
set (col2, col3, ..., coln) = ( 
  select tab.col2, tab.col3, ..., tab.coln
  from tablename tab
  where (tab.id = tablename.id + 1 and tab.t = tablename.t) or (tab.id = tablename.id - 1)
  order by tab.id desc limit 1
)  
where (col2, col3, ..., coln) = (0, 0, ..., 0)
  and exists (
        select 1 from tablename tab 
        where  (tab.id = tablename.id + 1 and tab.t = tablename.t) or (tab.id = tablename.id - 1)
      )

请参阅demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2018-09-22
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多