在论坛更新后,我留下了应该填写的空白字段。 我试图使用名为post的表中的字段更新名为thread的表。我需要处理由threadid,postid命令的post表。
Table: post
Field: postid - data is valid
Field: threadid - data is valid
Table: thread
Field: threadid - data is valid and matches post.threadid
Field: firstpostid - should be first post.postid found
Field: lastpostid - should be last post.postid found
Field: lastpost - should be last post.postid found
我尝试的所有内容都为firstpostid和lastpostid
产生相同的值这与我尝试建立一次更新一个字段的方法差不多。我无法正确设置订单。
UPDATE thread
INNER JOIN post ON post.threadid = thread.threadid
SET thread.firstpostid =
IF(thread.firstpostid > post.postid, post.postid, thread.firstpostid)
WHERE postid <> 0
任何指针都会很棒。感谢
答案 0 :(得分:0)
我们可以使用相关子查询,尽管这可能是效率最低的方法。为了获得合理的性能,我们肯定希望有适当的索引,例如:
... ON post (thread_id, post_id)
(以thread_id
和post_id
作为前导列的任何索引,按此顺序排列)
我们可以使用标量子查询来检索要分配给每列的post_id
值。 (在此上下文中,子查询必须是标量:查询必须最多返回一行包含单个值:
UPDATE thread t
SET t.firstpostid =
( SELECT p1.post_id
FROM post p1
WHERE p1.thread_id = t.thread_id
ORDER BY p1.thread_id, p1.post_id
LIMIT 0,1
)
, t.secondpostid =
( SELECT p2.post_id
FROM post p2
WHERE p2.thread_id = t.thread_id
ORDER BY p2.thread_id, p2.post_id
LIMIT 1,1
)
, t.lastpostid =
( SELECT p9.post_id
FROM post p9
WHERE p9.thread_id = t.thread_id
ORDER BY p9.thread_id DESC, p9.post_id DESC
LIMIT 0,1
)
“技巧”是在ORDER BY之后应用的LIMIT子句。
LIMIT 0,1
表示跳过0行并返回下一行
LIMIT 1,1
表示跳过1行并返回下一行
要获取最后一个post_id,我们会颠倒排序顺序(DESC
=降序,而默认ASC
=升序。)