繁体   English   中英

将数据从旧表迁移到新表查询

[英]Migrate data from old table to new table query

需要一点帮助来创建一个查询,该查询从mb_topics中获取topic_titletopic_content ,从mb_posts表中获取post_content ,然后将mb_topics.topic_title插入到forum_topics.topic_title (table.field), mb_topics.topic_contentmb_posts.post_content forum_posts表。

是否可以使用单个选择查询?

mb表:

CREATE TABLE IF NOT EXISTS `mb_posts` (
  `id` int(11) NOT NULL,
  `posted_by` bigint(20) NOT NULL DEFAULT '0',
  `topic_id` int(11) NOT NULL DEFAULT '0',
  `post_content` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `mb_topics` (
  `id` int(11) NOT NULL,
  `topic_title` varchar(75) NOT NULL DEFAULT '',
  `posted_by` bigint(20) NOT NULL DEFAULT '0',
  `topic_content` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

forum表:

CREATE TABLE IF NOT EXISTS `forum_posts` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `post_content` text NOT NULL,
  `post_date` datetime NOT NULL,
  `post_topic` int(11) NOT NULL,
  `post_by` int(11) unsigned NOT NULL
  PRIMARY KEY (`post_id`),
  KEY `post_topic` (`post_topic`),
  KEY `post_by` (`post_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `forum_topics` (
  `topic_id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_title` varchar(150) NOT NULL,
  `topic_by` int(11) unsigned NOT NULL
  PRIMARY KEY (`topic_id`),
  KEY `topic_by` (`topic_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

PHP:

$get_old_data_query=mysql_query('SELECT `title`, `content` FROM `mb_topics`');
while($old_data=mysql_fetch_assoc($get_old_data_query))
{
    $old_data_array[]=$old_data;
}

我想这样的事还可以吗?

<?php
$Old = mysql_query("SELECT * FROM Table WHERE Name = 'Name'");

while(mysql_fetch_array($Old)){
$Data = mysql_fetch_array($Old);
$Old1 = $Data['Name'];

mysql_query("INSERT INTO NewTable (Name) VALUES ('$Old1')");
}

以下查询将从mb_postsmb_topics表中获取数据,并将其插入forum_posts表中。

INSERT INTO forum_posts( post_content, post_topic, post_date, post_by ) 
SELECT MBP.post_content, MBT.id, NOW( ) , MBP.posted_by
FROM mb_posts AS MBP
LEFT JOIN mb_topics AS MBT ON MBP.topic_id = MBT.id

同样,以下查询将从旧表(mb_topics)到新表(forum_topics)中获取帖子主题。

INSERT INTO forum_topics( topic_title, topic_by) 
SELECT MBT.topic_title, MBT.posted_by
FROM mb_posts AS MBP
LEFT JOIN mb_topics AS MBT ON MBP.topic_id = MBT.id

这将是2个独立的查询,因为使用一个INSERT只能将其插入1个表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM