mysql从另一个表更新列值

im9ewurl  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(281)

邮递

+-----+-----+-----+
| tid | uid | pid |
+-----+-----+-----+
|   1 |   1 |   1 |
|   2 |   1 |   2 |
|   3 |   1 |   3 |
|   3 |   2 |   4 |
|   4 |   1 |   5 |
...
+-----+-----+-----+

线

+-----+---------+---------+
| tid | lastpid | lastuid |
+-----+---------+---------+
|   1 |       0 |       0 |
|   2 |       0 |       0 |
|   3 |       0 |       0 |
|   4 |       0 |       0 |
...
+-----+---------+---------+

我希望线程的结果是:

+-----+---------+---------+
| tid | lastpid | lastuid |
+-----+---------+---------+
|   1 |       1 |       1 |
|   2 |       1 |       2 |
|   3 |       2 |       4 |
...
+-----+---------+---------+

一句话怎么说?
post's tid=thead's tid,post max(pid)的pid,uid是thead的值。
我想从post.tid eq thread.tid的post max(pid)中获取pid和uid。并将pid,uid设置为替换线程的lastpid和lastuid。
根据最佳答案,我们重写了它来解决这个问题: UPDATE thread t INNER JOIN ( SELECT tid, uid AS last_uid, pid AS last_pid FROM post WHERE pid IN (SELECT max(pid) FROM post GROUP BY tid) ) p ON t.tid = p.tid SET t.lastuid = p.last_uid, t.lastpid = p.last_pid;

f45qwnt8

f45qwnt81#

您可以尝试更新连接:

UPDATE thread t
INNER JOIN
(
    SELECT tid, MAX(uid) AS max_uid, MAX(pid) AS max_pid
    FROM post
    GROUP BY tid
) p
    ON t.tid = p.tid
SET
    t.lastuid = p.max_pid,
    t.lastpid = p.max_uid;

如果你只是想做一个选择,那么上面可以稍加修改,基本上只需替换 UPDATE...SELECT .
请注意,似乎 lastuid 以及 lastpid 已在预期输出中交换。

相关问题