【问题标题】:Copy MySQL table and populate with additional fields复制 MySQL 表并填充其他字段
【发布时间】:2011-05-30 06:19:26
【问题描述】:

我想将现有的 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 中执行此类过程的建议或指导都会非常有帮助(如果可能的话)。

编辑:该技术的示例会有所帮助。我不需要上述的确切答案。我相信每个人都有更好的事情要做。

【问题讨论】:

    标签: mysql select insert


    【解决方案1】:

    刚刚遇到类似的问题。

    这个解决方案对我有用:

    INSERT INTO `new_thread` SELECT *,null,null FROM `thread` WHERE 1=1
    

    【讨论】:

      【解决方案2】:

      创建目标表(空):

      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;
      

      (未经测试)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-26
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        相关资源
        最近更新 更多