根据第一个 id 更新 id 的第二行
Update second amount of row with id based on the first id
我的原始数据如下:
sid id amount
1 12 30
2 45 30
3 45 50
4 78 80
5 78 70
所需的输出如下:
sid id amount
1 12 30
2 45 30
3 45 30
4 78 80
5 78 80
目的是取id第一次出现的金额,第二次出现时更新金额
我正在尝试以下代码:
UPDATE foo AS f1
JOIN
( SELECT cur.sl, cur.id,
cur.amount AS balance
FROM foo AS cur
JOIN foo AS prev
ON prev.id = cur.id
GROUP BY cur.tstamp
) AS p
ON p.id = a.id
SET a.amount = p.amount ;
将 table 加入到 returns 每个 id
的最小值 sid
的查询中,然后再次连接到它自身,这样您就可以得到具有该最小值 [= 的行12=]:
UPDATE tablename t1
INNER JOIN (
SELECT MIN(sid) sid, id
FROM tablename
GROUP BY id
) t2 ON t2.id = t1.id AND t2.sid < t1.sid
INNER JOIN tablename t3 ON t3.sid = t2.sid
SET t1.amount = t3.amount;
参见demo。
对于 MySql 8.0+,如果您使用 ROW_NUMBER()
window 函数,则只需 1 个连接即可完成:
UPDATE tablename t1
INNER JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY sid) rn
FROM tablename
) t2 ON t2.id = t1.id
SET t1.amount = t2.amount
WHERE t2.rn = 1;
参见demo。
我的原始数据如下:
sid id amount
1 12 30
2 45 30
3 45 50
4 78 80
5 78 70
所需的输出如下:
sid id amount
1 12 30
2 45 30
3 45 30
4 78 80
5 78 80
目的是取id第一次出现的金额,第二次出现时更新金额 我正在尝试以下代码:
UPDATE foo AS f1
JOIN
( SELECT cur.sl, cur.id,
cur.amount AS balance
FROM foo AS cur
JOIN foo AS prev
ON prev.id = cur.id
GROUP BY cur.tstamp
) AS p
ON p.id = a.id
SET a.amount = p.amount ;
将 table 加入到 returns 每个 id
的最小值 sid
的查询中,然后再次连接到它自身,这样您就可以得到具有该最小值 [= 的行12=]:
UPDATE tablename t1
INNER JOIN (
SELECT MIN(sid) sid, id
FROM tablename
GROUP BY id
) t2 ON t2.id = t1.id AND t2.sid < t1.sid
INNER JOIN tablename t3 ON t3.sid = t2.sid
SET t1.amount = t3.amount;
参见demo。
对于 MySql 8.0+,如果您使用 ROW_NUMBER()
window 函数,则只需 1 个连接即可完成:
UPDATE tablename t1
INNER JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY sid) rn
FROM tablename
) t2 ON t2.id = t1.id
SET t1.amount = t2.amount
WHERE t2.rn = 1;
参见demo。