mysql - 使用 mysql 中最旧行的数据更新最新行

标签 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

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

最佳答案

计划

  • select the minimum entries (maxs) grouped by columne1,
  • select the maximum entries (mins) grouped by columne1,
  • join calls to maxs to mins
  • set calls.columne2 value from mins data

查询

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

关于mysql - 使用 mysql 中最旧行的数据更新最新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31539983/

相关文章:

mysql - AutoIncrement PK 增量不规则

PHP串联后分页

python - 是否可以使用 python 连接 MySQL 数据库

php - 为什么我的 PHP PDO 函数插入一条 MySQL 记录会无限循环?

php - 在带有 PDO 的同一 mysql 语句中使用 'AND' 和 'OR'

mysql - MySql 中的嵌套查询

mysql - 加入时查询未返回所有结果

c# - 防止桌面应用程序上的多个相同用户登录

php - 如果条件在多行中匹配,则从映射表中获取数据

php - 在数据库字段中搜索