Max Hudson
Max Hudson

Reputation: 10206

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.

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):

User ID (id)
Password value (pass)

Old table 2 (oldtable2):

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

New table (newtable):

id
name
email
password

Upvotes: 0

Views: 244

Answers (4)

Linger
Linger

Reputation: 15048

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
)

Upvotes: 3

user2672373
user2672373

Reputation:

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

Upvotes: 0

Igor Borisenko
Igor Borisenko

Reputation: 3866

IN SQL-Server you can do it this way if NewTable not exists yet.

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

Upvotes: 0

Heberda
Heberda

Reputation: 820

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 :)

Upvotes: 2

Related Questions