如何解决复制MySQL表并填充其他字段
| 我想将一个现有的MySQL表复制到一个重复的表中,但是要有另外两个字段,这些字段由从其他查询中检索到的数据填充。它用于论坛软件,但从未捕获到线程的原始创建日期(它总是用最新的回复覆盖时间)。 所以我想使用现有的表“ threads”thread_id
thread_author
thread_subject
thread_last_reply_date
并创建具有相同结构但有两个额外字段的新表\'new_threads \':
thread_id
thread_author
thread_subject
thread_last_reply_date
thread_creation_date
thread_last_poster_id
可以从相关查询中填充thread_last_reply_date和thread_last_poster_id。例如,last_poster_id的查询为:
SELECT post_author FROM posts WHERE thread_id = ? AND post_date = thread_last_reply_date
并且对于thread_creation_date:
SELECT MIN(post_date) FROM posts WHERE thread_id = ?
从本质上讲,这就是我要使用PHP脚本执行的过程。一系列的SELECT,然后一个接一个地插入记录。关于如何在纯SQL中执行这种类型的处理的任何建议或方向都将非常有用(如果可能)。
编辑:该技术的示例将是有帮助的。我不需要上面的确切答案。我确定每个人都有更好的事情要做。
解决方法
要创建目标表(空):
CREATE TABLE new_threads
SELECT t.*,thread_creation_date date,thread_last_poster_id number
FROM thread where 1=0;
并填充它:
insert into new_threads(thread_id,thread_author,thread_subject,thread_last_reply_date,thread_creation_date,thread_last_poster_id)
(select t.*,min(p.post_date),(SELECT p1.post_author
FROM posts p1
WHERE p1.thread_id = t.thread_id
AND p1.post_date = t.thread_last_reply_date) thread_last_poster_id
from threads t,posts p
where t.thread_id = p.thread_id;
(未试)
, 只是有一个类似的问题。
此解决方案为我工作:
INSERT INTO `new_thread` SELECT *,null,null FROM `thread` WHERE 1=1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。