复制表a中的某些列并插入到表b中?
问题描述:
请有人可以帮助我一直在这个查询几个小时。我想从我的表ptb_registrations复制某些列,并将它们作为新行插入到ptb_users中。复制表a中的某些列并插入到表b中?
我ptb_registrations表看起来像这样:
id | username | password | firstname | lastname | email
1 dave password james tanner [email protected]
2 jonx10 gundam00 eric davies [email protected]
3 33csgge henry10 daniel gilmart [email protected]
这些列中,我只需要插入ID,名字,姓氏,电子邮件地址和密码不是username
。
所以我ptb_user表看起来像这样:
id | user_id | password | firstname | lastname | email
1 1 password james tanner [email protected]
2 2 gundam00 eric davies [email protected]
3 3 henry10 daniel gilmart [email protected]
ID是自动增量值,我想USER_ID有当数据被插入过(如果是相同的值auto_incremented id列因此,其中id是1 - user_id也将为1)
到目前为止,我已经尝试了不同的方式获取从ptb_registrations插入到ptb_users的列的负载,但没有任何工作适合我。
罐头有人请告诉我我错在哪里,谢谢。
// Make a safe query
$query ="insert into ptb_users(id, first_name)
select ptb_registrations.id, ptb_registrations.firstname
from ptb_registrations, temp
where ptb_users.id=temp.id;
";
mysql_query($query)or die('Could not update members: ' . mysql_error());
答
有没有办法保证你的新AUTO_INCREMENT
将以前的用户ID的匹配...如果序列中会发生什么情况?你最好的选择是在插入记录后重新分配新表的ID。
你的查询应该是这样的:
INSERT INTO ptb_user (user_id, password, firstname, lastname, email)
SELECT id, password, firstname, lastname, email
FROM ptb_registrations
ORDER BY id
附:我希望你不要将密码保存在明文。
[**请不要在新代码中使用'mysql_ *'函数**](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。 – Kermit 2013-03-14 19:07:49