mysql从另一个表更新列值

时间:2018-04-12 06:31:17

标签: mysql

+-----+-----+-----+
| 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 |
...
+-----+---------+---------+

你如何用一个陈述完成它? 帖子的tid = thead的tid,并发布max(pid)的pid,uid是thead的值。

我想从post.tid eq thread.tid的post max(pid)获得pid和uid。 并设置pid,uid来替换thread的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;

1 个答案:

答案 0 :(得分:3)

您可以尝试更新加入:

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即可。

请注意,lastuidlastpid似乎已在您的预期输出中进行了交换。