简体   繁体   English

将两列从一个表复制到另一个表

[英]Copying two columns from one table to another

Couldn't find exactly what I'm looking for anywhere else. 在其他任何地方都找不到我正在寻找的东西。

So I have table 1 所以我有表1

users
----------

id
username
password
bio
isuser
email

and table 2 和表2

wp_users
----------

id
user_login
nice_username
password
email

There are 500 rows in 'wp_users' table. “ wp_users”表中有500行。 I would like to copy 'id' and 'user_login' into the users table ('id' and 'username') for each row. 我想将每一行的“ id”和“ user_login”复制到用户表(“ id”和“ username”)中。

How can I do this? 我怎样才能做到这一点? MySQL isn't my strong point lol. MySQL不是我的强项。

UPDATE: I have updated the tables above as I tried to simplify it but in return got the wrong solution. 更新:我在尝试简化表格时更新了上面的表格,但得到的解决方案却是错误的。

You can use an INSERT - SELECT statement: 您可以使用INSERT - SELECT语句:

INSERT INTO `users` (id,username,password,bio,isuser,email) SELECT id,
user_login,null,null,null,null FROM `wp_users`;

You can put another fields or even static data on each field of the SELECT part. 您可以在SELECT部件的每个字段上放置另一个字段,甚至可以放置静态数据。 I've put nulls just to illustrate. 我将null只是为了说明。

Just remember that anything the SELECT fetches will be inserted in the table the INSERT statement says (so you can use clauses like WHERE , GROUP BY , HAVING , etc on the SELECT part). 只要记住SELECT提取的任何内容都会插入INSERT语句所说的表中(因此您可以在SELECT部分使用WHEREGROUP BYHAVING等子句)。

I believe you are looking for a simple insert statement: 我相信您正在寻找一个简单的插入语句:

INSERT INTO users (id,username)
SELECT W.id,
       W.user_login
FROM   wp_users W
WHERE  NOT EXISTS (SELECT NULL
                   FROM   users U
                   WHERE  U.ID = W.ID);

I am assuming the other columns in your users table are nullable, if not, you can add more columns to the select statement with the values in you'd like for the other columns. 我假设用户表中的其他列可以为空,如果不能,则可以向select语句添加更多列,并使用其他列中的值。

You haven't mentioned any other keys or constraints, so I have assumed there aren't any. 您没有提到任何其他键或约束,因此我假设没有任何键或约束。

I have also provided a check in the WHERE clause to see if a row already exists for the same ID, so you only insert a row for each ID once. 我还提供了WHERE子句中的检查,以查看同一ID是否已经存在一行,因此您只需为每个ID插入一行即可。

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

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