简体   繁体   English

将(两个表的联接)插入另一个表

[英]Insert (join of two tables) into a different table

I have two tables with a bunch of stuff I don't need in them. 我有两个桌子,上面放着一堆我不需要的东西。 One has info about a user and the other their password. 一个拥有有关用户的信息,另一个拥有其密码。

I have a new table that will store both their info and password together. 我有一个新表,它将他们的信息和密码一起存储。

Additionally, the user info table has separate fields for first name and last name and I need to combine them to place them in the "name" column and add a space between them. 此外,用户信息表具有用于名字和姓氏的单独字段,我需要将它们组合以将它们放在“名称”列中,并在它们之间添加一个空格。

I need to do this without disrupting (modifying) either of the old tables. 我需要做到这一点而又不破坏(修改)任何一个旧表。

I also need to be able to add an integer value to the id column. 我还需要能够向id列添加一个整数值。

I would think the basic syntax looks like this, but don't know what to do past here 我认为基本语法看起来像这样,但是不知道过去该怎么做

INSERT INTO newtable (id, name, email, password) VALUES ((JOIN statement?), (JOIN statement?), (JOIN statement?), (JOIN statement?))

How can I accomplish this with a script? 如何使用脚本完成此操作?

Old table 1 ( oldtable1 ): 旧表1( oldtable1 ):

User ID (id)
Password value (pass)

Old table 2 ( oldtable2 ): 旧表2( oldtable2 ):

User ID (id)
First name (fname)
Last name (lname)
Email (email)

New table ( newtable ): 新表( newtable ):

id
name
email
password
SELECT id, name, email, password INTO NewTable 
FROM 
(
  SELECT o1.id, CONCAT(o2.fname, ' ', o2.lname), o2.email,  o1.Password
  FROM oldTable1 AS o1
    JOIN oldTable2 AS o2
    ON o1.id = o2.id
)
SELECT ID, Password, Name, Email INTO NewTable 
FROM (SELECT ID, Password
FROM oldTable1
FULL OUTER JOIN oldTable2
ON oldTable1.ID=oldTable2.ID)

Try that... I'm no genius but it should work :) 试试吧...我不是天才,但它应该可以工作:)

IN SQL-Server you can do it this way if NewTable not exists yet. 在SQL Server中,如果NewTable还不存在,您可以通过这种方式进行操作。

SELECT IDENTITY(INT,1,1) id, name,email,password
INTO newtable
FROM oldtable1 ot1
     join oldtable2 ot2 on ot1.UserID=ot2.UserID

and if it already exists 如果它已经存在

insert into newtable (name,email,password)
select name,email,password
FROM oldtable1 ot1
         join oldtable2 ot2 on ot1.UserID=ot2.UserID

Are you sure you need a new table for join of two tables? 您确定需要一个新表来连接两个表吗? Ever heard of views? 听说过意见吗? You can use that. 您可以使用它。

CREATE VIEW myView AS
SELECT oldtable1.id, oldtable1.pass, oldtable2.fname, oldtable2.email
FROM oldtable1 JOIN oldtable2 ON oldtable1.id = oldtable2.id

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

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