使用mysql

时间:2015-07-21 13:10:04

标签: mysql

如何使用旧条目中的数据更新表格中的某些字段?

示例表:

    id | timestamp    | columne1| columne2
    ---------------------------------------
    1  | 2015-07-20...| 078888  | *****
    2  | 2015-07-19...| 155896  | value 2.2
    3  | 2015-07-07...| 278831  | value 2.3
    4  | 2015-07-01...| 078888  | value 2.4

我正在尝试使用相同columne2第4行中的值更新第1行中的columne2。

1 个答案:

答案 0 :(得分:2)

<强>计划

  
      
  • 选择按columne1,
  • 分组的最小条目(最大值)   
  • 选择按columne1,
  • 分组的最大条目(分钟)   
  • 加入对maxs到分钟的调用
  •   
  • 从mins数据中设置calls.columne2值
  •   

<强>查询

update
calls c
inner join
(
  select c1.*, q1.min_ts, q1.max_ts
  from calls c1
  inner join
  ( select columne1, min(`timestamp`) min_ts, max(`timestamp`) as max_ts from calls group by columne1 ) q1
  on c1.columne1 = q1.columne1
  where c1.`timestamp` = q1.max_ts
) maxs
on c.id = maxs.id
inner join
(
  select c1.*, q1.min_ts, q1.max_ts
  from calls c1
  inner join
  ( select columne1, min(`timestamp`) min_ts, max(`timestamp`) as max_ts from calls group by columne1 ) q1
  on c1.columne1 = q1.columne1
  where c1.`timestamp` = q1.min_ts
) mins
on maxs.columne1 = mins.columne1
set c.columne2 = mins.columne2
;

<强>输出

+----+------------------+----------+-----------+
| id |    timestamp     | columne1 | columne2  |
+----+------------------+----------+-----------+
|  1 | 2015-07-20 12:00 |   078888 | value 2.4 |
|  2 | 2015-07-19 12:00 |   155896 | value 2.2 |
|  3 | 2015-07-07 12:00 |   278831 | value 2.3 |
|  4 | 2015-07-01 12:00 |   078888 | value 2.4 |
+----+------------------+----------+-----------+

<强> sqlfiddle